Javascript:滚动到光标并在 contenteditable div 中粘贴内容

Ash*_*shD 5 html javascript

我有一个 div,其 contenteditable 属性值设置为 true。当我在此 contenteditable 中粘贴一些文本时,我可以将鼠标位置保留在粘贴文本的末尾。当粘贴大量文本时,文本可能会溢出可见区域。请注意,宽度如果固定并且元素沿 Y 方向滚动。

我无法弄清楚如何确定粘贴后的光标(不是鼠标)Y 位置,以便我可以滚动到该位置。粘贴不一定总是发生在最后,因此滚动到底部并不在所有情况下都有帮助。

对此的任何提示将不胜感激。

Dmi*_*rov 8

const scrollSelectionIntoView = () => {
  // Get current selection
  const selection = window.getSelection();

  // Check if there are selection ranges
  if (!selection.rangeCount) {
    return;
  }

  // Get the first selection range. There's almost never can be more (instead of firefox)
  const firstRange = selection.getRangeAt(0);

  // Sometimes if the editable element is getting removed from the dom you may get a HierarchyRequest error in safari
  if (firstRange.commonAncestorContainer === document) {
    return;
  }

  // Create an empty br that will be used as an anchor for scroll, because it's imposible to do it with just text nodes
  const tempAnchorEl = document.createElement('br');

  // Put the br right after the caret position
  firstRange.insertNode(tempAnchorEl);

  // Scroll to the br. I personally prefer to add the block end option, but if you want to use 'start' instead just replace br to span
  tempAnchorEl.scrollIntoView({
    block: 'end',
  });

  // Remove the anchor because it's not needed anymore
  tempAnchorEl.remove();
};
Run Code Online (Sandbox Code Playgroud)