代码之家  ›  专栏  ›  技术社区  ›  MarkB29

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

  •  176
  • MarkB29  · 技术社区  · 16 年前

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

    我通过谷歌找到了一些零碎的东西,但没有防弹的。

    基本上类似jquery插件的东西是理想的,所以我可以

    $("#myinput").caretPosition()
    
    8 回复  |  直到 7 年前
        1
  •  203
  •   CommonSenseCode    8 年前

    更容易更新:

    使用 field.selectionStart example in this answer .

    感谢@commonsensecode指出这一点。


    老回答:

    找到了这个解决方案。不基于jquery,但集成到jquery没有问题:

    /*
    ** Returns the caret (cursor) position of the specified text field.
    ** 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.selectionStart;
    
      // Return results
      return iCaretPos;
    }
    
        2
  •  115
  •   Rob W jminkler    14 年前

    好极了,谢谢麦克斯。

    如果有人想使用jquery,我已经将他的答案中的功能打包到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);
    
        3
  •  51
  •   CommonSenseCode    7 年前

    很容易

    更新答案

    使用 selectionStart 它是 compatible with all major browsers .

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

    更新:只有在未定义类型或输入上键入“text”时,此操作才有效。

        4
  •  26
  •   Rajesh Paul    12 年前

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

    <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

        5
  •  14
  •   George    13 年前
       (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);
    
        6
  •  14
  •   YakovL Naresh Kumar Nakka    8 年前

    现在有一个很好的插件: The Caret Plugin

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

        7
  •  10
  •   pmrotule    10 年前

    这里有一些很好的答案,但我认为您可以简化代码并跳过检查 inputElement.selectionStart 支持:它不仅在IE8和更早版本上受支持(请参见 documentation )小于电流的1% browser usage .

    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);
    }
    
        8
  •  2
  •   dhaupin    9 年前

    也许除了光标位置之外,还需要一个选定的范围。这是一个简单的函数,您甚至不需要jquery:

    function caretPosition(input) {
        var start = input[0].selectionStart,
            end = input[0].selectionEnd,
            diff = end - start;
    
        if (start >= 0 && start == end) {
            // do cursor position actions, example:
            console.log('Cursor Position: ' + start);
        } else if (start >= 0) {
            // do ranged select actions, example:
            console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
        }
    }
    

    假设您希望在输入发生更改或鼠标移动光标位置时调用它(在本例中,我们使用jquery .on() )出于性能原因,最好添加 setTimeout() 或者像下划线之类的东西 _debounce() 如果事件正在涌入:

    $('input[type="text"]').on('keyup mouseup mouseleave', function() {
        caretPosition($(this));
    });
    

    如果你想试试,这里有一把小提琴: https://jsfiddle.net/Dhaupin/91189tq7/