美文网首页
vue中实现按下键盘上下键实现li标签背景色的切换

vue中实现按下键盘上下键实现li标签背景色的切换

作者: 哒哒哒哒da | 来源:发表于2022-07-26 09:47 被阅读0次
键盘按下上下键,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;
}

相关文章

网友评论

      本文标题:vue中实现按下键盘上下键实现li标签背景色的切换

      本文链接:https://www.haomeiwen.com/subject/ihcoirtx.html