自定义元素可以扩展输入元素吗?

Jos*_*ock 16 javascript html5 web-component

使用Web组件规范,是否可以扩展特定类型的<input>元素?

这个问题类似于我的问题,但它只指定了如何扩展button元素,而不是文本输入或<input>标记的任何其他变体.

在我的情况下,我想扩展一个checkbox(<input type="checkbox" />)或一个单选按钮(<input type="radio" />),以便围绕相同的核心输入元素功能包装更复杂的UI,但我没有看到任何方法使用extends提供的语法通过document.registerElement.在我看来,你应该能够做如下的事情:

document.registerElement('x-checkbox', {
    prototype: Object.create(HTMLInputElement.prototype),
    extends: 'input[type=checkbox]'
});
Run Code Online (Sandbox Code Playgroud)

但是,这个特定的案例似乎没有记录或解释我能找到的任何地方,而且我相信这个例子在实践中不起作用.

Der*_*會功夫 13

is如果要扩展另一个标准HTML元素,则必须使用该属性.由于没有"复选框"的元素,你不能扩展之类的东西input[type=checkbox]radio.扩展inputelement(HTMLInputElement)并在createdCallback:中指定类型:

<body>
    <input is="totally-not-checkbox">   <!-- Custom Checkbox #1 -->
</body>
Run Code Online (Sandbox Code Playgroud)
var proto = Object.create(HTMLInputElement.prototype);
proto.createdCallback = function() {
    this.type = "checkbox";
    this.addEventListener("change", this.toggleZoom);
};
proto.toggleZoom = function(){
    $(this).toggleClass("zoom");                        //FYI $ is jQuery
};

var nCB = document.registerElement("totally-not-checkbox", {
    prototype: proto,
    extends: 'input'
});

document.body.appendChild(new nCB());  //Custom Checkbox #2
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/DerekL/5utco0en/

由于自定义元素的扩展HTMLInputElement,所有原始属性和方法都是继承的.看一下这个演示:http://jsfiddle.net/DerekL/6gtLp8p5/

proto.toggleZoom = function(e){
    $(this).toggleClass("zoom");
    console.log(this, this.checked);
};
Run Code Online (Sandbox Code Playgroud)

this.checked将返回正确的checked值,就像原始复选框一样.