最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript: Scroll to cursor post a paste in contenteditable div - Stack Overflow

programmeradmin0浏览0评论

I have a div with contenteditable attribute value set to true. When I paste some text in this contenteditable, I am able to keep the mouse position at the end of the pasted text. When there is a large amount of text pasted, the text may overflow the visible area. Note that width if fixed and the element scrolls in the Y direction.

I am unable to figure how to determine the cursor (not the mouse) Y position post the paste so that I can scroll to that position. It is not necessarily true that the paste will always happen at the end, so scroll to bottom is not going to help out in all cases.

Any hints on this will be appreciated.

I have a div with contenteditable attribute value set to true. When I paste some text in this contenteditable, I am able to keep the mouse position at the end of the pasted text. When there is a large amount of text pasted, the text may overflow the visible area. Note that width if fixed and the element scrolls in the Y direction.

I am unable to figure how to determine the cursor (not the mouse) Y position post the paste so that I can scroll to that position. It is not necessarily true that the paste will always happen at the end, so scroll to bottom is not going to help out in all cases.

Any hints on this will be appreciated.

Share Improve this question asked Nov 18, 2017 at 0:37 AshDAshD 1,1742 gold badges14 silver badges29 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9
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.monAncestorContainer === 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();
};
发布评论

评论列表(0)

  1. 暂无评论