键盘按下上下键,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;
}