wingmeng / front-end-quiz

前端小测试答题收集
0 stars 0 forks source link

DOM基础测试40:列表点击、方向键操作 #38

Open wingmeng opened 4 years ago

wingmeng commented 4 years ago

题目:

image

我的回答:

> 在线 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();