我正在尝试使用焦点功能在文本字段中设置光标。我进行了一些研究,但提供的解决方案似乎都无法在Google Chrome中正常工作。在Internet Explorer和Firefox中,此解决方案运行良好:

js:

$('#Search').focus(function() {
  var SearchInput = $('#Search');
  var strLength= SearchInput.val().length;
  SearchInput.focus();
  SearchInput[0].setSelectionRange(strLength, strLength);
});

HTML:
<input type="text" id="Search" value="Hello World" />

这是我的jsfiddle的链接。

有什么办法可以在Google Chrome浏览器中使它正常工作吗?

最佳答案

看来,当您聚焦输入时,焦点事件是在放置光标之前触发的,一种怪异的解决方法是使用setTimeout,如下所示:

$('#Search').focus(function() {
    setTimeout((function(el) {
        var strLength = el.value.length;
        return function() {
            if(el.setSelectionRange !== undefined) {
                el.setSelectionRange(strLength, strLength);
            } else {
                $(el).val(el.value);
            }
    }}(this)), 0);
});

试试这个 fiddle : http://jsfiddle.net/esnvh/26/

编辑为0毫秒超时,因为@SparK指出这足以将其推送到执行队列的末尾。

关于javascript - 如何在谷歌浏览器中的输入文本末尾设置光标位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21881509/

10-10 13:11