Can't restore selection with window.getSelection() and range after re-rendering contenteditable div

ε祈祈猫儿з 提交于 2021-01-29 19:31:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!