如何使自定义元素在Firefox中工作? [英] How to get custom elements working in Firefox?

查看:70
本文介绍了如何使自定义元素在Firefox中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个基本的自定义元素示例.它可以在Chrome中运行,但不能在Firefox中运行.有没有办法让它在Firefox中运行(没有聚合物,但可能有某种形式的polyfill)?

I have this basic custom element example. It is working in Chrome, however not in Firefox. Is there a way to get it working in Firefox (without polymer but maybe some kind of polyfill)?

我还启用了dom.webcomponents.enabled标志,但未成功.

I also enabled the dom.webcomponents.enabled flag without any success.

此问题解决后,我创建了一个带有完整代码的存储库: https://github.com/peplow/webcomponent-example/

Since this is solved, I created a repository, with the complete code: https://github.com/peplow/webcomponent-example/

自定义元素html文件:

Custom element html file:

<template id="template">
  <button id="button">Hallo</button>
  <style media="screen">
    button{
      color:red;
    }
  </style>
</template>

<script>
    var localDoc = document.currentScript.ownerDocument;
    class toggleButton extends HTMLElement{

      constructor(){
        super();
        this.shadow = this.attachShadow({mode: 'open'});
        var template = localDoc.querySelector('#template');
        this.shadow.appendChild(template.content.cloneNode(true));

        this.shadow.querySelector('button').onclick = function(){
          alert("Hello World");
        }
      }

      static get observedAttributes() {return ['name']; }

      attributeChangedCallback(attr, oldValue, newValue) {
        if (attr == 'name') {
          this.shadow.querySelector('#button').innerHTML = newValue;
        }
      }

    }

    customElements.define('x-toggle', toggleButton);
</script>

使用文件的位置:

<!DOCTYPE html>
<html>
  <head>
    <link rel="import" href="element.html">
    <meta charset="utf-8">
  </head>
  <body>
    <x-toggle name="Hello World"></x-toggle>
  </body>
</html>

推荐答案

Firefox尚未发布自定义元素v1,这是最新标准,是将customElements.define()指定为定义元素的方式的工具(与v0相对)它使用了document.registerElement(),并且在Firefox中带有dom.webcomponents.enabled标志可用.

Firefox has not yet shipped Custom Elements v1, which is the latest standard and is what specifies customElements.define() as the way to define an element (as opposed to v0 which used document.registerElement() and is what is available with the dom.webcomponents.enabled flag in Firefox).

Chrome是当前唯一本地支持自定义元素v1的浏览器,但所有其他主要浏览器都支持它.

Chrome is currently the only browser that supports Custom Elements v1 natively, but all other major browsers are supportive of it.

Firefox具有自定义元素v1支持的打开错误.

Firefox has an open bug for Custom Elements v1 support.

同时,最好的选择是将自定义元素v1 Polyfill 用于浏览器,不支持.您可以使用'customElements' in window功能检测自定义元素v1"支持.

In the meantime, your best bet is to use the Custom Elements v1 Polyfill for browsers that don't support it. You can feature-detect Custom Elements v1 support with 'customElements' in window.

这篇关于如何使自定义元素在Firefox中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆