admin管理员组文章数量:1393083
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 badges1 Answer
Reset to default 9const 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();
};
本文标签: htmlJavascript Scroll to cursor post a paste in contenteditable divStack Overflow
版权声明:本文标题:html - Javascript: Scroll to cursor post a paste in contenteditable div - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744745814a2622870.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论