问题
I have contenteditable div. After some actions contenteditable is re-rendered. Before re-rendering of the div I store range data to object like this:
this.rangeData = {
anchorNodeKey: null,
anchorOffset: null,
focusNodeKey: null,
focusOffset: null,
isCollapsed: null,
};
I store keys of nodes instead of anchorNode
. After re-rendering of the div I get nodes by this key and use them for creating range and restore selection like this:
const range = document.createRange();
const anchorNode = this.getNodeByKey(this.rangeData.anchorNodeKey);
range.setStart(anchorNode, this.rangeData.anchorOffset);
const focusNode = this.getNodeByKey(this.rangeData.focusNodeKey);
range.setEnd(focusNode, this.rangeData.focusOffset);
range.collapse(this.rangeData.isCollapsed);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
Caret is placed after re-rendering at the appropriate place but I can't restore selection (for example, selected word become unselected and caret is placed at the end of such word).
Selection
object has property type
( https://developer.mozilla.org/en-US/docs/Web/API/Selection/type ) which can has "Range" value but I can't find how to set it.
What have I missed?
来源:https://stackoverflow.com/questions/61011651/cant-restore-selection-with-window-getselection-and-range-after-re-rendering