两个contentEdible的div 里面都是多行文本 上下键的操作

新手上路,请多包涵

image.png

当我有两个可编辑的div 并且都是个多行文本 都是撑满宽度后自动换行的多行文本,这个时候我的光标位置在这个第三行 红色标记的中间位置 那这个时候 我怎么能拿到这个光标距离最左侧有多少个字符。
因为我需要记住这个第一次光标距离左侧的位置 然后方向键下 到第一个可编辑div的最后一行的时候再按下方向键下 要跳到下一个可编辑的div里面 并把光标设置成上面 光标第一次距离最左侧的位置 。。。。大佬们有思路的提供一下啊 小弟想好久了

看wolai.com notion.so都是实现的 跨contentEditable的时候也能正确定位鼠标位置 这个是怎么做到的

阅读 2.1k
2 个回答

参考一下stackoverflow的这个回答https://stackoverflow.com/a/3...

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;
}
#caretposition {
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contentbox" contenteditable="true">Click me and move cursor with keys or mouse</div>
<div id="caretposition">0</div>
<script>
  var update = function() {
    $('#caretposition').html(getCaretPosition(this));
  };
  $('#contentbox').on("mousedown mouseup keydown keyup", update);
</script>
新手上路,请多包涵

最后解决了 document.caretRangeFromPoint 这个API可以实现

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题