我确定我遗漏了规范中的一些基本内容,但是在Safari上运行的Mac上构建了大量自定义元素后,我发现它们在Firefox和Chrome上不起作用。我想念什么?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>NoCE</title>
<script>
class NoCE extends HTMLElement {
constructor(args) {
super();
}
connectedCallback() {
this.innerHTML = "<p>It Works</p>";
}
attributeChangedCallback(name, oldValue, newValue, namespaceURI) {}
disconnectedCallback() {}
adoptedCallback() {}
static get observedAttributes() { return []; }
}
customElements.define("no-ce", NoCE, { extends: "div" });
</script>
</head>
<body>
<no-ce>
No custom elements
</no-ce>
</body>
</html>
在Safari中,页面显示“有效”。在Firefox和Chrome中,它显示“无自定义元素”(在Mac OS X上运行。)
Safari 12.0.2 Firefox 64.0.2 铬71.0.3578.98
答案 0 :(得分:5)
您将自治自定义元素(又称新HTML标记)的定义与自定义内置元素(又称标准HTML元素扩展名)混合使用,它们的语法略有不同
对于自治自定义元素:
@MID
对于自定义内置class NoCE extends HTMLElement
...
customElements.define( 'no-ce', NoCE )
...
<no-ce><no-ce>
元素:
<div>
Safari不会实现自定义的buit-it元素,因此将忽略class NoCE extends HTMLDivElement
...
customElements.define( 'no-ce', NoCE, { extends: 'div'} )
...
<div is='no-ce'></div>
选项,并将您的代码作为简单的自治自定义元素进行处理。
另一方面,Chrome和Firefox将忽略您的自定义元素定义,因为它不正确。
如果要使自定义元素继承自extends
,则应首先用<div>
扩展NoCE
类,然后使用HTMLDivElement
语法。 (但是如果没有polyfill,那将无法在Safari中使用。)
或者,如果您想使用基本的<div is="no-ce">
行为创建自己的HTML标签,则可以定义一个自主的自定义元素,并以<div>
CSS样式对其应用。
{display:block}
class ACE extends HTMLElement {
connectedCallback() {
this.attachShadow( { mode: 'open' } )
.innerHTML = `<style> :host { display: block } </style>
Autonomous CE works`
}
}
customElements.define( 'a-ce', ACE )
class CBE extends HTMLDivElement {
connectedCallback() {
this.attachShadow( { mode: 'open' } )
.innerHTML = `Customized DIV works`
}
}
customElements.define("c-ce", CBE, { extends: "div" } )