获取文本输入字段中的光标位置(以字符为单位)

Mar*_*B29 199 html javascript jquery

如何从输入字段中获取插入位置?

我通过谷歌发现了一些零碎的东西,但没有任何防弹措施.

基本上像jQuery插件这样的东西是理想的,所以我可以简单地做

$("#myinput").caretPosition()
Run Code Online (Sandbox Code Playgroud)

bez*_*max 233

更新更容易:

使用field.selectionStart 此答案中的示例.

感谢@commonSenseCode指出这一点.


老答案:

找到了解决方案.不是基于jquery,但将它集成到jquery没有问题:

/*
** Returns the caret (cursor) position of the specified text field (oField).
** Return value range is 0-oField.value.length.
*/
function doGetCaretPosition (oField) {

  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {

    // Set focus on the element
    oField.focus();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange();

    // Move selection start to 0 position
    oSel.moveStart('character', -oField.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }

  // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;

  // Return results
  return iCaretPos;
}
Run Code Online (Sandbox Code Playgroud)

  • `else if(oField.selectionStart || oField.selectionStart =='0')`可能是`else if(typeof oField.selectionStart ==='number')` (7认同)

Mar*_*B29 117

很好,非常感谢Max.

如果有人想使用它,我已经将他的答案中的功能包装到jQuery中.

(function($) {
    $.fn.getCursorPosition = function() {
        var input = this.get(0);
        if (!input) return; // No (input) element found
        if ('selectionStart' in input) {
            // Standard-compliant browsers
            return input.selectionStart;
        } else if (document.selection) {
            // IE
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            return sel.text.length - selLen;
        }
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

  • @Mic不,不是在jQuery插件中.在插件中,"this"指的是一个完整的包装集.他的代码仍然是错误的,它应该只是`this.get(0)`.他的代码可能仍然有用,因为重新包装一个包装的集合什么都不做. (4认同)
  • 是不是`input = $(this).get(0)`与`input = this`相同? (3认同)

Com*_*ode 78

很容易

更新的答案

使用selectionStart,它与所有主流浏览器兼容.

document.getElementById('foobar').addEventListener('keyup', e => {
  console.log('Caret at: ', e.target.selectionStart)
})
Run Code Online (Sandbox Code Playgroud)
<input id="foobar" />
Run Code Online (Sandbox Code Playgroud)

更新:仅当未定义类型或输入时键入="text"时才有效.

  • 很棒,但当输入类型为数字时,在 Firefox 或 Chrome 中不起作用。 (5认同)
  • 如果我使用鼠标更改位置,它不会打印在控制台中。有办法解决吗? (4认同)
  • 与本页上的其他答案一样,如果您开始突出显示某个选项并将光标移动到该选项的末尾,则会给出错误的值。选择开始和选择结束与光标位置不同。光标可能位于一端或另一端。 (3认同)
  • @EugeneBarsky只需为click事件添加一个新的事件监听器.您可以随时检查`.selectionStart`属性(`document.getElementById('foobar').selectionStart`),它不必在事件监听器中. (2认同)

Raj*_*aul 26

有一个非常简单的解决方案.尝试以下代码并验证结果 -

<html>
<head>
<script>
    function f1(el) {
    var val = el.value;
    alert(val.slice(0, el.selectionStart).length);
}
</script>
</head>
<body>
<input type=text id=t1 value=abcd>
    <button onclick="f1(document.getElementById('t1'))">check position</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我给你fiddle_demo

  • `slice`是一个相对昂贵的操作,它不会给这个'解决方案'增加任何东西 - "el.selectionStart"相当于你的切片的长度; 回来吧.而且,其他解决方案更复杂的原因是因为它们处理不支持`selectionStart`的其他浏览器. (13认同)
  • 'selectionStart'在IE中不起作用 (6认同)
  • @ user2782001:我错过了 - 我的主要关注点是函数名称.`f1`和'user2782001'一样有意义. (4认同)
  • 我已经辞去了必须使用带有这样的变量名称的代码的工作。 (3认同)
  • @Michael Scheper - 你的意思是“el”代表元素,“val”代表值?这些都是很常见的... (2认同)

Geo*_*rge 14

   (function($) {
    $.fn.getCursorPosition = function() {
        var input = this.get(0);
        if (!input) return; // No (input) element found
        if (document.selection) {
            // IE
           input.focus();
        }
        return 'selectionStart' in input ? input.selectionStart:'' || Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
     }
   })(jQuery);
Run Code Online (Sandbox Code Playgroud)


Jen*_*sen 14

现在有一个很好的插件:插入插件

然后你可以使用$("#myTextBox").caret()或通过它设置位置$("#myTextBox").caret(position)

  • 好吧,我让它适用于<input type ="text"id ="myTextBox"/>并使用上面的代码. (4认同)

pmr*_*ule 10

这里有一些很好的答案,但我认为你可以简化代码并跳过检查inputElement.selectionStart支持:仅在IE8及更早版本(参见文档)上不支持它,它代表当前浏览器使用率的不到1%.

var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;

// and if you want to know if there is a selection or not inside your input:

if (input.selectionStart != input.selectionEnd)
{
    var selectionValue =
    input.value.substring(input.selectionStart, input.selectionEnd);
}
Run Code Online (Sandbox Code Playgroud)