首页 > 解决方案 > customElements 在谷歌浏览器中不起作用

问题描述

我正在尝试在我的网站中使用一些自定义元素,并且在 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>

我希望这会创建一个自定义元素类,并将DOM 中的MyElement所有元素转换为该类的实例,一旦添加到自定义元素注册表,就会将原来的红色组件变成绿色。my-element在 Firefox 中,这正是发生的情况,但在 google chrome 中,它保持红色。控制台表明该元素已添加到注册表中,但从未调用过它的构造函数。

我错过了什么吗?这是chrome的问题,还是我做错了什么?我怎样才能让它在那里工作?

标签: javascripthtmlgoogle-chromecustom-element

解决方案


这里的工作示例

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函数以确保执行
  • {extends:"div"}_customElements.define

推荐阅读