gpt4 book ai didi

javascript - 自定义选择标签

转载 作者:行者123 更新时间:2023-12-03 06:27:25 24 4
gpt4 key购买 nike

例如,我想创建一个自定义选择标签,并且希望它继承所有属性。我尝试过:

document.registerElement('my-select', {
prototype: Object.create(HTMLSelectElement.prototype),
extends: 'select'
});

document.registerElement('my-option', {
prototype: Object.create(HTMLOptionElement.prototype),
extends: 'option'
});

但是好像不行。我做错了什么?

最佳答案

您只需提供构建自定义选择组件的抽象方法,实现将包括创建两个原型(prototype),即选择和选项,最后将其与我们将在 HTML 页面中声明的自定义选择框 Hook 。

查看此 fiddle 链接以获取演示:https://jsfiddle.net/47gzo8kt/

Javascript:

var CustomizedSelectOptionPrototype = Object.create(HTMLElement.prototype);
document.registerElement('cust-select-option', { prototype: CustomizedSelectOptionPrototype});

var CustomizedSelectProto = Object.create(HTMLSelectElement.prototype);
CustomizedSelectProto.createdCallback = function() {
if (!this.getAttribute('tabindex')) {
this.setAttribute('tabindex', 0);
}
this.placeholder = document.createElement('span');
this.appendChild(this.placeholder);

var selected = this.querySelector('cust-select-option[selected]');
this.placeholder.textContent = selected ? selected.textContent : (this.getAttribute('placeholder') || '');
};
document.registerElement('cust-select', { prototype: CustomizedSelectProto, extends:"select"});

HTML:

<label>
Customized Select Box:
<select is="cust-select" placeholder="Please select an option">
<option selected value="1">English</option>
<option value="2">French</option>
<option value="3">Hindi</option>
</select>
</label>

关于javascript - 自定义选择标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com