Extending <option>

最后都变了- 提交于 2019-12-21 20:38:45

问题


I'm trying to extend the 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"
});

Here's a demo of the code.

but apparently that doesn't work because it already has a user agent 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.

I have never seen this error and I thought it lets you attach multiple shadow roots. Why is it happening and is there a way to make it work?


回答1:


You were right: it was possible to attach multiple shadow roots.

... But this possibility was removed from Chrome to comply with the new version of the Shadow DOM specification (v1), which is now shared with other browser vendors (Mozilla, Microsoft, Apple).

That's why you never saw this error before. It was added to the Living Standard:

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

As a workaround, you have to not use Shadow DOM, or to create a new custom element that doesn't extends the <option> element.



来源:https://stackoverflow.com/questions/39599461/extending-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!