将光标定位在文本输入框的左侧

3

可能重复:
jQuery在文本区域中设置光标位置

当一个带有文本的输入框获得焦点时,光标会出现在右侧文本的末尾。如何使光标在获得焦点时位于文本左侧?

我看到了使用 "setCursor" 的示例,但是我收到了 setCursor 未定义的错误。

<input type="text" class="myInput">
    Tabbing into this should put my cursor at the left!
</input>

setCursor抛出了一个未定义的错误。

$(".myInput").focus(function(){
    var node = $(this);
    setCursor(node, 0);
});

很接近了,但是那个问题的答案是从2009年的,所以现在可能有更简洁的处理方法 :) - Don P
当焦点在带有文本的输入框上时,光标会从文本右侧末尾开始。如果使用Tab键进入输入框,则通常会选择输入框中的所有文本;如果使用鼠标单击,则光标会放置在单击的位置。 - nnnnnn
3
实际上,我认为在这方面没有什么改变,即使是在 HTML5 中也是如此。 - AndreKR
1个回答

3

试试这个...

<input type="text" class="myInput" value="Tabbing into this should put my cursor at the left!" />

(function(){
        jQuery.fn.setSelection = function(selectionStart, selectionEnd) {
            if(this.length == 0) return this;
            input = this[0];

            if (input.createTextRange) {
                var range = input.createTextRange();
                range.collapse(true);
                range.moveEnd('character', selectionEnd);
                range.moveStart('character', selectionStart);
                range.select();
            } else if (input.setSelectionRange) {
                input.focus();
                input.setSelectionRange(selectionStart, selectionEnd);
            }

            return this;
        }
        jQuery.fn.setCursorPosition = function(position){
            if(this.length == 0) return this;
            return $(this).setSelection(position, position);
        }
        $(".myInput").focus(function(){
            $(this).setCursorPosition(0);
        });
    })();

希望现在它能工作了


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接