Shadow-root sibling elements disappear on attachShadow() call

耗尽温柔 提交于 2021-01-05 08:37:11

问题


When I call host.attachShadow({mode: 'open'}) on a div containing a few elements inside, the contents of the div seemingly disappears. The elements are still visible from devtools but are no longer visible on screen.

It doesn't matter if i fill the shadowRoot with anything; as soon as the shadow is attached the div's children disappear.

Demo on codepen: https://codepen.io/anon/pen/VrBdOe

Why does the content disappear? I've seen it on websites so I know it's possible somehow. See the code for https://www.polymer-project.org/2.0/start/quick-tour for example, the <pw-shell> node has a shadow-root and several siblings co-existing. What's going on there?


回答1:


The Shadow DOM content will replace the original DOM subtree of the host where it (the shadow root) is attached. That's the expected behaviour of a Shadow DOM (hence this name).

You can make it appear by using the element in the Shadow DOM.

host.attachShadow( { mode: 'open' } )
    .innerHTML = 'Original DOM: <slot></slot>, in the Shadow DOM'
<div id=host>
Lite DOM
</div>

You should read the tutorial about Shadow DOM for further details.



来源:https://stackoverflow.com/questions/47500157/shadow-root-sibling-elements-disappear-on-attachshadow-call

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