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();
};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744745814a4591288.html
评论列表(0条)