为何Shadow DOM环境下Selection.isCollapsed属性始终返回true?
Selection.isCollapsed在Shadow DOM中的兼容性异常问题
根据Web API规范说明,Selection.isCollapsed在存在当前选中文本时应当返回false。该属性在常规DOM环境下表现符合预期,但在Shadow DOM中,即便已有文本被选中,isCollapsed似乎始终返回true。
值得注意的是,在Shadow DOM中调用getSelection()可以正确返回当前选中内容,anchorNode、anchorOffset等属性均正常,唯独isCollapsed始终返回不符合预期的true。
相关示例代码如下:
document.getElementById("app").innerHTML = "<h1>Hello DOM</h1>"; window.customElements.define( "example-component", class extends HTMLElement { constructor() { super(); const mountPoint = document.createElement("div"); this.attachShadow({ mode: "open" }); mountPoint.innerHTML = `<h1>hello Shadow DOM</h1>`; this.shadowRoot?.appendChild(mountPoint); } } ); document.addEventListener("selectionchange", () => { console.log("dom selectionchange"); console.log(window.getSelection()); console.log("shadow dom selectionchange"); console.log( document.querySelector("example-component").shadowRoot.getSelection() ); });
本次测试使用Chrome 92浏览器。
目前Selection API与Shadow DOM、Web Components确实存在若干兼容问题,多数功能可正常运行,仅该属性表现异常。
内容的提问来源于stack exchange,提问作者zgreen
相关产品推荐
相关产品推荐

