我正在尝试在我的网站中使用一些自定义元素,并且在 Firefox 中到目前为止效果很好。然而,在谷歌浏览器中,它只是默默地失败 - 我的自定义元素的构造函数从未被调用,并且它也不会抛出错误。
假设这个最小的例子:
<!DOCTYPE html>
<html>
<head>
<script>
class MyElement extends HTMLDivElement {
constructor(){
super();
this.style.background = "#00ff00";
console.log("Created custom element!");
}
}
function addCustomElement(){
customElements.define("my-element",MyElement,{extends:"div"});
console.log("Added MyElement to custom element registry!");
}
</script>
</head>
<body onload="addCustomElement()">
<my-element style="display:block;width:100px;height:100px;background:#ff0000"></my-element>
</body>
</html>
我希望这会创建一个自定义元素类 MyElement
并在添加到自定义元素后将 DOM 中的所有 my-element
元素转换为该类的实例注册表,将原本红色的组件变成绿色。在 Firefox 中,这正是发生的情况,但在 google chrome 中,它保持红色。控制台指示该元素已添加到注册表中,但从未调用其构造函数。
我错过了什么吗?这是chrome的问题,还是我做错了什么?我怎样才能让它在那里工作?
最佳答案
这里是工作示例
class MyElement extends HTMLElement {
constructor(){
super();
this.style.background = "#00ff00";
console.log("Created custom element!");
}
}
function addCustomElement(){
customElements.define("my-element", MyElement)
console.log("Added MyElement to custom element registry!");
}
// add call here, because onload did not work for me
addCustomElement()
https://jsfiddle.net/so98Lauz/1/
更改:
- 扩展 HTMLElement 而不是 HTMLDivElement
- 在js中调用
addCustomElement
函数以确保执行 - 从
customElements.define
中删除了{extends:"div"}
关于javascript - 自定义元素在谷歌浏览器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59398462/