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;
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容