如何在Firefox中使用外部CSS来样式化ShadowDOM元素?

3
我正在尝试构建一个自定义HTML元素。问题是我不能够使用外部CSS样式来应用于Shadow DOM元素。该代码在Chrome中运行正常,但在Firefox中却不行。

var proto = Object.create(HTMLElement.prototype);

proto.createdCallback = function() {

    console.log('Element creation started...');

    var inputTextElement = document.createElement('input');
    inputTextElement.type = 'text';
    inputTextElement.className = 'simpleElem';

    // Shadow DOM root
    var shadowRoot = this.createShadowRoot();

    shadowRoot.appendChild(inputTextElement);

    console.log('Element creation ended...');

};

var SimpleElement = document.registerElement('simple-element', { prototype: proto });
simple-element {
}

simple-element::shadow  .simpleElem {
    height: 30px;
    margin: 0px;
    padding: 0px;
    width: 180px;
}
<!doctype html>
<html>
    <head>
        <title>HTML5 | Custom Elements</title>
        <link type="text/css" rel="stylesheet" href="simple-elem.css">
        <script type="text/javascript" src="simple-elem.js"></script>
    </head>
    <body>
        <simple-element></simple-element>
    </body>
</html>

无法确定Firefox出现了什么问题。
3个回答

2
更新:FF Shadow DOM支持已经到来。
火狐浏览器还没有支持Shadow DOM,请参见CanIUse.com。我建议继续使用Chrome。 编辑:FF Nightly有一些支持,可以手动启用。

2
正如Gábor Imre所指出的那样,Firefox默认情况下未启用Shadow DOM,因为它仍在开发中。但是,您可以使用polyfill在所有不支持它的浏览器中获得相当好的Shadow DOM行为。如果这样做,您将需要使用polyfill-next-selector来获取您想要的行为。

1

尽管Shadow DOM在Firefox中已经得到了支持(使两个其他答案无效),但是在Firefox 72中,您现在可以通过part属性和::part()伪元素分别定位自定义/Shadow DOM元素:

//this JS boilerplate adapted from MDN
let template = document.getElementById("simple-element");
globalThis.customElements.define(template.id, class extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content);
  }
});
simple-element::part(shadow) {
    height: 30px;
    margin: 0;
    padding: 0;
    width: 180px;
    background: green;
}
<template id="simple-element">
    <div part="shadow">Hi</div>
</template>

<simple-element></simple-element>

显然,这段代码看起来与你的问题代码有很大不同,因为自2014年以来,Shadow DOM规范/实现已经发生了很大变化。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接