获取内容可编辑元素的文本光标位置

时间:2021-07-25 23:10:54

Here is some code that will get the text cursor position by clicking a button:

这是一些代码,通过单击按钮获取文本光标位置:

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

I want to create something very similar to this but in a content editable element instead

我想创建一些非常类似的东西,但是在内容可编辑元素中

<span contenteditable="true">abcd</span>

I have spent some time researching this, but I can't seem to find any working code for all browsers. Any ideas?

我花了一些时间研究这个,但我似乎找不到所有浏览器的任何工作代码。有任何想法吗?

1 个解决方案

#1


0  

<html>
<head>
<script>
    function f1(el) {
    alert(getCaretPosition(el));
}
   

 function getCaretPosition(editableDiv) {
  var caretPos = 0,
    sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      if (range.commonAncestorContainer.parentNode == editableDiv) {
        caretPos = range.endOffset;
      }
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    if (range.parentElement() == editableDiv) {
      var tempEl = document.createElement("span");
      editableDiv.insertBefore(tempEl, editableDiv.firstChild);
      var tempRange = range.duplicate();
      tempRange.moveToElementText(tempEl);
      tempRange.setEndPoint("EndToEnd", range);
      caretPos = tempRange.text.length;
    }
  }
  return caretPos;
}
</script>
</head>
<body>
<span id="test" contenteditable="true">abcd</span>
    <button onclick="f1(document.getElementById('test'))">check position</button>
</body>
</html>

#1


0  

<html>
<head>
<script>
    function f1(el) {
    alert(getCaretPosition(el));
}
   

 function getCaretPosition(editableDiv) {
  var caretPos = 0,
    sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      if (range.commonAncestorContainer.parentNode == editableDiv) {
        caretPos = range.endOffset;
      }
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    if (range.parentElement() == editableDiv) {
      var tempEl = document.createElement("span");
      editableDiv.insertBefore(tempEl, editableDiv.firstChild);
      var tempRange = range.duplicate();
      tempRange.moveToElementText(tempEl);
      tempRange.setEndPoint("EndToEnd", range);
      caretPos = tempRange.text.length;
    }
  }
  return caretPos;
}
</script>
</head>
<body>
<span id="test" contenteditable="true">abcd</span>
    <button onclick="f1(document.getElementById('test'))">check position</button>
</body>
</html>