// set default selected, by tab html selected attribute this.selected = this._findFirstSelectedTab() || 0 }
// tab click event _onTitleClick(e) { if (e.target.slot === 'tab') { // now click Element index this.selected = this.tabs.indexOf(e.target) } }
// tab keydown event _onKeydown(e) { switch(e.code) { // up left case'ArrowUp': case'ArrowLeft': e.preventDefault() // --, if it's 0 idx = length - 1 else idx var idx = this.selected - 1 idx = idx < 0 ? this.tabs.length - 1 : idx // click event this.tabs[idx].click() break; // down right case'ArrowDown': case'ArrowRight': e.preventDefault() // ++ by & tab click event var idx = this.selected + 1 this.tabs[idx % this.tabs.length].click() break; default: break; } }
// find tab html attribute selected set now Tab _findFirstSelectedTab() { let selectedIdx // for for (const [i, tab] ofthis.tabs.entries()) { // set role tab.setAttribute('role', 'tab') // if tab has selected, nowTab is i if (tab.hasAttribute('selected')) { selectedIdx = i } } return selectedIdx }
// set tab toggle function _selected(idx = null) { // for for(let i = 0, tab; tab = this.tabs[i]; ++i) { // if idx === i equal true let selected = idx === i // set attribute tab.setAttribute('aria-selected', selected) this.panels[i].setAttribute('aria-hidden', !selected) } } }
if (customElements) customElements.define('custom-tabs', customTab) elseconsole.log('不支持 custom') </script>