在shadowRoot里获取光标(selection)信息
文章目录
3大浏览器,3种不一样的处理方式😅
getSelectionAndRange() {
let selection = document.getSelection();
if (!selection) return null;
// 规范 getComposedRanges, CH--FF--SF17
if ('getComposedRanges' in selection) {
const [firstRange] = selection.getComposedRanges(this.#shadowRoot);
if (!firstRange || !this.#editor.contains(firstRange.startContainer)) return null;
const range = document.createRange();
range.setStart(firstRange.startContainer, firstRange.startOffset);
range.setEnd(firstRange.endContainer, firstRange.endOffset);
return [selection, range] as const;
}
if (selection.type === 'None') {
return null;
}
// shadowRoot.getSelection() CH53FF--SF--
if ('getSelection' in this.#shadowRoot) {
selection = this.#shadowRoot.getSelection();
if (selection.type === 'None') return null;
return [selection, selection.getRangeAt(0)] as const;
}
// selection 可穿透shadowRoot CH--FF??SF--
if (selection.anchorNode === this.#editor || this.#editor.contains(selection.anchorNode)) {
return [selection, selection.getRangeAt(0)] as const;
}
return null;
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论