UNPKG

lu2

Version:

Simple and flexible UI component library based on native HTML and JavaScript

80 lines (66 loc) 2.13 kB
/** * @author zhangxinxu * @create 2022-01-20 * @description 开关选择交互的泛支持 **/ /**/(async () => { /**/ if (!CSS.supports('overflow-anchor:auto') || !CSS.supports('offset:none')) { /**/ await import('../safari-polyfill.js'); /**/ } class UiCheckbox extends HTMLInputElement { static get observedAttributes () { return ['extends', 'checked', 'disabled']; } get extends () { return this.hasAttribute('extends'); } set extends (val) { this.toggleAttribute('extends', val); } render () { if (!this.extends) { return; } [...this.labels].forEach(label => { label.classList[this.checked ? 'add' : 'remove']('active'); label.classList[this.disabled ? 'add' : 'remove']('disabled'); label.setAttribute('role', 'button'); }); } attributeChangedCallback () { this.render(); } constructor () { super(); // 事件处理 this.addEventListener('change', () => { this.render(); }); this.render(); const propChecked = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked'); Object.defineProperty(UiCheckbox.prototype, 'checked', { ...propChecked, set (value) { // 赋值 propChecked.set.call(this, value); // 触发渲染 this.render(); } }); } connectedCallback () { // 全局事件 this.dispatchEvent(new CustomEvent('connected', { detail: { type: 'ui-checkbox' } })); this.isConnectedCallback = true; } } if (!customElements.get('ui-checkbox')) { customElements.define('ui-checkbox', UiCheckbox, { extends: 'input' }); } /**/})();