![](/img/trans.png)
[英]How to not render the content in the <content> tag in Shadow DOM?
[英]shadow DOM not showing content. How to make content visible in DOM?
如您所见,我想动态添加内容,但 shadow DOM 未显示内容如何使内容可见? 我想让内容可见。
let shadow = document.querySelector('#nameTag').createShadowRoot(); let content_area = document.querySelector("#nameTag"); content_area.innerHTML = '<p>Hello world!</p>'; let template = document.querySelector('#nameTagTemplate'); shadow.appendChild( template.content.cloneNode(true) ); shadow.appendChild( template.content );
h2{ color: red; font-size: 24px; font-weight: bold; }
<h2>Hello world!</h2> <div id="nameTag"></div> <template id="nameTagTemplate"> <div class="outer"> <div class="name"></div> </div> </template>
首先,您应该使用 V1 函数attachShadow
而不是 V0 函数createShadowRoot
。 V0 规范已弃用,大多数浏览器均不支持,并将很快从 Chrome 中删除。
其次,您的模板中需要一个<slot>
, <div id="nameTag"></div>
将显示在其中。
第三,您将模板的克隆和原始模板附加到 shadowRoot 中。 不确定你想这样做,所以我在我的例子中去掉了它。
let shadow = document.querySelector('#nameTag').attachShadow({mode:'open'}); let content_area = document.querySelector("#nameTag"); content_area.innerHTML = 'I show in the slot'; let template = document.querySelector('#nameTagTemplate'); shadow.appendChild( template.content.cloneNode(true) );
h2{ color: red; font-size: 24px; font-weight: bold; } #nameTag { border: 1px dashed blue; }
<h2>Hello world!</h2> <div id="nameTag"></div> <template id="nameTagTemplate"> <div class="outer"> <div class="name"><slot></slot></div> </div> </template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.