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

时间:2017-11-18 00:37:54

标签: javascript html

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

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

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

1 个答案:

答案 0 :(得分:3)

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();
};
相关问题