【问题标题】:Position the cursor on the left of a text input [duplicate]将光标定位在文本输入的左侧[重复]
【发布时间】:2012-10-24 21:47:59
【问题描述】:

可能重复:
jQuery Set Cursor Position in Text Area

当带有文本的输入被聚焦时,光标从右侧文本的末尾开始。如何使光标位于焦点的左侧?

我见过使用“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 年开始的,所以现在可能有更清洁的方法来处理它:)
  • “当输入有文本时,光标从右侧文本的末尾开始” - 它通常不会选择所有文本如果是 Tab 键,则输入,或者如果使用鼠标,则将光标准确地放在您单击的位置?
  • @DonnyP 实际上我认为这没有任何改变,即使是 HTML5。

标签: jquery html css input


【解决方案1】:

试试这个..

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

希望它现在可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多