如何从输入字段中获取插入符号位置?
我通过谷歌找到了一些零碎的东西,但没有防弹。
基本上像 jQuery 插件这样的东西是理想的,所以我可以简单地做
$("#myinput").caretPosition()
如何从输入字段中获取插入符号位置?
我通过谷歌找到了一些零碎的东西,但没有防弹。
基本上像 jQuery 插件这样的东西是理想的,所以我可以简单地做
$("#myinput").caretPosition()
更简单的更新:
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;
}
使用selectionStart. 它与所有主要浏览器兼容。
document.getElementById('foobar').addEventListener('keyup', e => {
  console.log('Caret at: ', e.target.selectionStart)
})
<input id="foobar" />
这仅在未定义类型type="text"或type="textarea"输入时有效。
如果有人想使用它,我已将bezmax 答案中的功能包装到 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);
得到了一个非常简单的解决方案。尝试使用以下代码验证结果-
<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>
我给你fiddle_demo
现在有一个很好的插件:The Caret Plugin
然后您可以使用$("#myTextBox").caret()或通过设置获取位置$("#myTextBox").caret(position)