前端开发过程中,经常需要这样的场景。用JS实现将光标定位于输入框最右侧。
[b]场景一:编辑图片的描述文字[/b]
[img]http://files.jb51.net/file_images/article/201212/201212040958388.png[/img]
[b]场景二[/b]:Script.aculo.us的Ajax.InPlaceEditor类。双击可编辑,编辑后离开可自动更新该区域。
以上场景都需要JS实现将光标定位于输入框最右侧,却不是通过鼠标点入输入框内。
我们知道实现最基本的方法是HTMLElement的focus方法。如下
<p>
<input type="text" value="hello"/>
</p>
<script>
var input = document.getElementsByTagName('input')[0];
input.focus();
</script>
打开该页面会发现,光标位于输入框的最左侧。效果如下
[img]http://files.jb51.net/file_images/article/201212/201212040958389.png[/img]
而现在要实现的是将光标定位于输入框最右侧,需要三个步骤。
[i][b]1,调用focus方法[/b][/i]
[i][b]2,value赋值为空[/b][/i]
[i][b]3,之前的input的值再赋给自己[/b][/i]
<p>
<input type="text" value="hello"/>
</p>
<script>
var input = document.getElementsByTagName('input')[0];
var val = input.value;
input.focus();
input.value = '';
input.value = val;
</script>
运行后效果如图,光标在深入框最右侧
[img]http://files.jb51.net/file_images/article/201212/2012120409583810.png[/img]