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);
});
4

1 回答 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);
        });
    })();

希望它现在可以工作

于 2012-11-05T04:46:27.463 回答