扩展 <option>

Extending <option>

我正在尝试扩展 HTMLOptionElement

<template id="cOptionTemplate">
    <content></content>
</template>

<select>
    <option is="custom-option">Test</option>
</select>
var cOption = document.registerElement('custom-option', {
    prototype: Object.create(HTMLOptionElement.prototype, {
        createdCallback: {
            value: function() {
                var template = document.getElementById("cOptionTemplate")
                var clone = document.importNode(template.content, true);
                this.createShadowRoot().appendChild(clone);
            }
        },
        attributeChangedCallback: {
            value: function (attrName, oldVal, newVal){
                switch(attrName){
                    case "attr1":
                        console.log(this);
                }
            }
        }
    }),
    extends: "option"
});

这是代码的 a demo

但显然这不起作用,因为它已经有一个用户代理 shadowRoot?

Uncaught InvalidStateError: Failed to execute 'createShadowRoot' on 'Element': Shadow root cannot be created on a host which already hosts an user-agent shadow tree.

我从未见过此错误,我认为它可以让您附加多个影子根。为什么会发生这种情况,是否有办法让它发挥作用?

你是对的:可以附加多个影子根。

...不过这个可能性was removed来自Chrome 遵守新版ShadowDOM规范(v1),现在已经和其他浏览器厂商共享了( Mozilla、微软、苹果)。

这就是您以前从未见过此错误的原因。这是 added to the Living Standard:

  1. If context object is a shadow host, then throw an InvalidStateError.

作为解决方法,您不得使用 Shadow DOM,或者创建一个不扩展 <option> 元素的新自定义元素。