Open wingmeng opened 4 years ago
> 在线 Demo <
const viewList = { init() { this.input = document.getElementById('input'); this.list = document.getElementById('list'); this.listItems = this.list.querySelectorAll('li'); this.selectedIdx = -1; this.clickHandle(); this.keyingHandle(); }, clickHandle() { this.listItems.forEach((li, index) => { li.addEventListener('click', () => this.doSelect(index)); }); }, keyingHandle() { document.addEventListener('keydown', ({ keyCode }) => { const maxIndex = this.listItems.length - 1; let index = this.selectedIdx; if (keyCode === 38) { // ↑ index-- } else if (keyCode === 40) { // ↓ index++ } index = index < 0 ? maxIndex : index; index = index > maxIndex ? 0 : index; this.doSelect(index); }); }, doSelect(index) { const curLi = this.listItems[index]; const selectedIdx = this.selectedIdx < 0 ? 0 : this.selectedIdx; this.listItems[selectedIdx].classList.remove('selected'); curLi.classList.add('selected'); this.input.value = curLi.innerText; this.selectedIdx = index; } }; viewList.init();
题目:
我的回答:
> 在线 Demo <