js 方向键 让列表切换
时间: 2023-08-16 12:09:37 浏览: 50
你可以使用 JavaScript 监听键盘事件,来实现方向键让列表切换的功能。具体实现步骤如下:
1. 获取需要切换的列表元素,例如 ul 标签下的 li 子元素。
2. 给 document 对象添加键盘事件监听函数,当键盘按下时触发。
3. 在监听函数中判断按下的键是方向键,并记录当前选中的列表项的索引。
4. 根据按下的方向键更新选中的列表项的索引。
5. 将选中的列表项设置为 active 样式,其他列表项取消 active 样式。
以下是一个简单的示例代码:
```html
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
<script>
const items = document.querySelectorAll('.item');
let currentIndex = 0;
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowUp') {
currentIndex = (currentIndex - 1 + items.length) % items.length;
} else if (event.key === 'ArrowDown') {
currentIndex = (currentIndex + 1) % items.length;
}
items.forEach((item, index) => {
if (index === currentIndex) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
});
</script>
```
在上述示例中,我们使用了 class="active" 样式来标记当前选中的列表项。通过按下方向键,可以实现选中列表项的切换。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)