vue中實現按下鍵盤上下鍵實現li標簽背景色的切換

鍵盤按下上下鍵,li標簽紅色背景可以上下切換
<ul>
    <li v-for="item in list" :key="item" :class="{active:index==item}">
        {item}}
    </li>
</ul>
  data: {
    list: [1, 2, 3, 4, 5],
    index: 1,
  },
  mounted() {
    document.addEventListener("keydown", (e) => {
      if (e.keyCode == 38) {
        if (this.index > 1) {
          this.index--;
        } else {
          this.index = 5;
        }
      } else if (e.keyCode == 40) {
        if (this.index < 5) {
          this.index++;
        } else {
          this.index = 1;
        }
      }
    });
  },
li {
  height: 50px;
  line-height: 50px;
}
.active {
  background-color: #f00;
}

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容