我正在尝试使用ShadowDomv1(与https://github.com/webcomponents/webcomponentsjs和https://github.com/webcomponents/shadycss一起使用),但是它不起作用。
ShadowDom本身可以工作,但是css没有封装(如我们在h2
css规则中所见)。
它可以在Chrome和Safari上正常运行(但它们本机都支持ShadowDomv1)。
我是否想念某些东西还是不可能?
这是jsbin:http://jsbin.com/maqohoxowu/edit?html,output
和代码:
<script type="text/javascript" src="https://rawgithub.com/webcomponents/webcomponentsjs/master/webcomponents-hi-sd-ce.js"></script>
<style type="text/css">
h2 {
color: red;
border-bottom: 1px black dotted;
}
</style>
<h2>h2 red and dotted</h2>
<my-element>
</my-element>
<template id="myElementTemplate">
<style scope="my-element">
h2 {color: blue}
</style>
<div>
<h2>h2 blue and not dotted !</h2> <!-- Should not be dotted because of the encapsulation -->
</div>
</template>
<script type="text/javascript">
ShadyCSS.prepareTemplate(myElementTemplate, 'my-element');
class MyElement extends HTMLElement {
connectedCallback() {
ShadyCSS.styleElement(this);
if (!this.shadowRoot) {
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(document.importNode(myElementTemplate.content, true));
}
ShadyCSS.styleElement(this);
}
}
customElements.define("my-element", MyElement);
</script>
最佳答案
您可以使用CustomStyleInterface将文档级样式仅应用于非Shadow DOM:
const CustomStyleInterface = window.ShadyCSS.CustomStyleInterface;
CustomStyleInterface.addCustomStyle(document.querySelector('style.doc-level'));
class MyElement extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(document.importNode(myElementTemplate.content, true));
}
}
customElements.define("my-element", MyElement);
<script src="https://rawgithub.com/webcomponents/webcomponentsjs/master/webcomponents-hi-sd-ce.js"></script>
<script src="https://rawgit.com/webcomponents/shadycss/master/custom-style-interface.min.js"></script>
<style class="doc-level">
h2 {
color: red;
border-bottom: 1px black dotted;
}
</style>
<h2>h2 red and dotted</h2>
<my-element></my-element>
<template id="myElementTemplate">
<style>
h2 {color: blue}
</style>
<div>
<h2>h2 blue and not dotted !</h2>
</div>
</template>