ContentEditable in Shadow DOM?

有些话、适合烂在心里 提交于 2019-12-21 05:11:18

问题


I'm trying to create a Polymer element for contenteditable.

I create a contenteditable div, place this.innerHTML there, and it becomes editable. All good with polyfills, e.g. in Firefox. But it doesn't work in Chrome 35 with native Shadow DOM.

Well, it is still editable, but neither document.execCommand nor window.getSelection is working.

  • document.execCommand does nothing.
  • window.getSelection().getRangeAt(0).toString() is defined but empty.
  • No error is shown.

So I cannot style the selection.

Does anybody know whether it's possible to make a custom editable element or not? What am I doing wrong? Maybe there's another way to work with contenteditable in modern/future web?


回答1:


According to the spec 1 selection is somewhat open ended for implementors. It does mention:

Accordingly, selections may only exist within one node tree, because they are defined by a single range. The selection, returned by the window.getSelection() method never returns a selection within a shadow tree.

The getSelection() method of the shadow root object returns the current selection in this shadow tree.

Have you tried the shadow root's getSelection()?




回答2:


you can use this:

const selection = shadowRoot.getSelection();
const range = selection.getRangeAt(0)
console.log(range.toString())


来源:https://stackoverflow.com/questions/23882272/contenteditable-in-shadow-dom

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