如何将光标移动到文本框的前面,其中包含文本

How do I move the cursor to the front of a textbox which has text in it?

本文关键字:文本 前面 包含 光标 移动      更新时间:2023-09-26

我有这样一个文本框:

<input type="text" name="url" id="url-input" />

和下面的代码:

var inputText = "Hello World";
$(document).ready(function() {
  $("#url-input").focus();
  $("#url-input").val(inputText);
});

实际上,光标显示在文本框末尾的"Hello World"后面(无论我以何种顺序添加焦点或更改值)。我怎样才能把它移到前面呢?

感谢

编辑 -这是jsFiddle: http://jsfiddle.net/dmRND/

在体面的web浏览器中,您可以访问代表选择的selectionStartselectionEnd属性。当它们都是0时,则不选择,并在开始处添加插入符号:

$("#url-input").prop('selectionStart', 0)
               .prop('selectionEnd', 0);
http://jsfiddle.net/efek3/

jQuery的另一件事是链接:$(...).func1().func2(),所以你只需要选择器一次。

jQuery的另一个特点是大多数函数都支持对象作为参数,所以你也可以这样做:

$("#url-input").prop({ selectionStart: 0,
                       selectionEnd:   0 });

我使用这个小的jquery插件:https://gist.github.com/DrPheltRight/1007907