获取 HTML 输入中的插入符位置?

发布于 2024-10-16 21:24:25 字数 24 浏览 4 评论 0原文

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

How do I get the index of the text caret in an input?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

逆夏时光 2024-10-23 21:24:25

-> 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>

-> 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>
有木有妳兜一样 2024-10-23 21:24:25

下面将为您提供选择的开始和结束作为字符索引。它适用于文本输入和文本区域,并且由于 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 ); 

The following will get you the start and end of the selection as character indices. It works for text inputs and textareas, and is slightly complicated because of IE's strange handling of line breaks.

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 ); 
温馨耳语 2024-10-23 21:24:25

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

然后你可以调用 $ ("#myTextBox").caret();

There is now a nice jQuery plugin for this: Caret plugin

Then you can just call $("#myTextBox").caret();

夢归不見 2024-10-23 21:24:25

我们在旧的 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;
}

We had used something like this for an old javascript application, but I haven't tested it in a couple years:

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;
}
夜夜流光相皎洁 2024-10-23 21:24:25

获取当前插入符位置的坐标(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< /a>

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

Get coordinates (css: left:x , top:y) of the current caret position in order to position an element (e.g. show tooltip at caret position)

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

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

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

丿*梦醉红颜 2024-10-23 21:24:25

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

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

Working example of getting cursor point in text box:

function textbox()
{
    var ctl = document.getElementById('Javascript_example');
    var startPos = ctl.selectionStart;
    var endPos = ctl.selectionEnd;
    alert(startPos + ", " + endPos);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文