内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我正在尝试使用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>
您好,如果是使用组件自己编写的代码,可以使用 spark 中的 pipeline 功能,将多个功能串成一个流水线,再把流水线导出为 pmml 模型。详见 https://github.com/jpmml/jpmml-sparkml。