【问题标题】:Get caret position in HTML input?在 HTML 输入中获取插入符号的位置?
【发布时间】:2011-06-23 03:36:36
【问题描述】:

如何获取输入中文本插入符号的索引?

【问题讨论】:

    标签: javascript html caret


    【解决方案1】:

    ->selectionStart

    <!doctype html>
        
    <html>
      <head>
        <meta charset = "utf-8">
    
        <script type = "text/javascript">
          window.addEventListener ("load", function () {
            var input = document.getElementsByTagName ("input");
            
            input[0].addEventListener ("keydown", function () {
              alert ("Caret position: " + this.selectionStart);
              
              // You can also set the caret: this.selectionStart = 2;
            });
          });
        </script>
        
        <title>Test</title>
      </head>
    
      <body>
        <input type = "text">
      </body>
    </html>
    

    【讨论】:

    • 好吧,监听器应该在 keyup 上注册并且它不处理新行(textarea),但这正是现代浏览器所要求的。
    • 您还需要输入的 selectionDirection 以在 selectionDirection 向后时获取插入符号位置,即您在文本框中向左选择,以便 selectionStart 是插入符号,但是当 selectionDirection 向前时插入符号将是在 selectionEnd。
    • 如果使用keydown,则需要根据key是否为方向键来调整输出
    • @inta 如果一个或多个字符被突出显示或选择,是否有任何实用的方法来检测或预测keydown 事件的实际选择?刚刚意识到selectionStart !== selectionEnd 应该可以解决问题
    • @oldboy 是的,这行得通。请记住,当前按下的键不会包含在您的选择中(例如,如果您使用 shift+箭头进行选择)。如果您想获得最终选择,请使用“keyup”事件。
    【解决方案2】:

    我们曾经在一个旧的 javascript 应用程序中使用过类似的东西,但我已经有几年没有测试过了:

    function getCaretPos(input) {
        // Internet Explorer Caret Position (TextArea)
        if (document.selection && document.selection.createRange) {
            var range = document.selection.createRange();
            var bookmark = range.getBookmark();
            var caret_pos = bookmark.charCodeAt(2) - 2;
        } else {
            // Firefox Caret Position (TextArea)
            if (input.setSelectionRange)
                var caret_pos = input.selectionStart;
        }
    
        return caret_pos;
    }
    

    【讨论】:

    • 在 IE 中似乎是一致的 21 个字符。通过调整,那里似乎很好,但在 FF 中是不准确的。 http://jsfiddle.net/zqNpV/
    【解决方案3】:

    以下内容将为您提供选择的开始和结束作为字符索引。它适用于文本输入和文本区域,并且由于 IE 对换行符的奇怪处理而稍微复杂。

    function getInputSelection(el) {
        var start = 0, end = 0, normalizedValue, range,
            textInputRange, len, endRange;
    
        if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
            start = el.selectionStart;
            end = el.selectionEnd;
        } else {
            range = document.selection.createRange();
    
            if (range && range.parentElement() == el) {
                len = el.value.length;
                normalizedValue = el.value.replace(/\r\n/g, "\n");
    
                // Create a working TextRange that lives only in the input
                textInputRange = el.createTextRange();
                textInputRange.moveToBookmark(range.getBookmark());
    
                // Check if the start and end of the selection are at the very end
                // of the input, since moveStart/moveEnd doesn't return what we want
                // in those cases
                endRange = el.createTextRange();
                endRange.collapse(false);
    
                if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                    start = end = len;
                } else {
                    start = -textInputRange.moveStart("character", -len);
                    start += normalizedValue.slice(0, start).split("\n").length - 1;
    
                    if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                        end = len;
                    } else {
                        end = -textInputRange.moveEnd("character", -len);
                        end += normalizedValue.slice(0, end).split("\n").length - 1;
                    }
                }
            }
        }
    
        return {
            start: start,
            end: end
        };
    }
    
    var textBox = document.getElementById("textBoxId");
    textBox.focus();
    alert( getInputSelection(textBox).start ); 
    

    【讨论】:

    • @NadavB:你确定你传递给函数的值是 DOM 输入还是 textarea 元素?
    • @TimDown 它的内容可编辑 div。它也应该起作用吗?
    • @NadavB:不。这是 contenteditable 的大致等效项:stackoverflow.com/a/4812022/96100
    【解决方案4】:

    现在有一个不错的 jQuery 插件:Caret plugin

    那你可以直接拨打$("#myTextBox").caret();

    【讨论】:

      【解决方案5】:

      在文本框中获取光标点的工作示例:

      function textbox()
      {
          var ctl = document.getElementById('Javascript_example');
          var startPos = ctl.selectionStart;
          var endPos = ctl.selectionEnd;
          alert(startPos + ", " + endPos);
      }
      

      【讨论】:

        【解决方案6】:

        获取当前插入符号位置的坐标(css:left:x , top:y)以定位元素(例如,在插入符号位置显示工具提示)

        function getCaretCoordinates() {
          let x = 0,
            y = 0;
          const isSupported = typeof window.getSelection !== "undefined";
          if (isSupported) {
            const selection = window.getSelection();
            // Check if there is a selection (i.e. cursor in place)
            if (selection.rangeCount !== 0) {
              // Clone the range
              const range = selection.getRangeAt(0).cloneRange();
              // Collapse the range to the start, so there are not multiple chars selected
              range.collapse(true);
              // getCientRects returns all the positioning information we need
              const rect = range.getClientRects()[0];
              if (rect) {
                x = rect.left; // since the caret is only 1px wide, left == right
                y = rect.top; // top edge of the caret
              }
            }
          }
          return { x, y };
        }
        

        演示:https://codesandbox.io/s/caret-coordinates-index-contenteditable-9tq3o?from-embed

        参考:https://javascript.plainenglish.io/how-to-find-the-caret-inside-a-contenteditable-element-955a5ad9bf81

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多