使用js,默认选中筛选的第一个元素,也可以通过上一下下一个选中某个元素,选中的元素设置不同的样式
时间: 2023-06-20 07:10:31 浏览: 42
可以通过以下代码实现:
HTML部分:
```html
<select id="mySelect">
<option value="option1">选项1</option>
<option value="option2">选项2</option>
<option value="option3">选项3</option>
<option value="option4">选项4</option>
</select>
```
JavaScript部分:
```javascript
// 获取select元素
const select = document.getElementById('mySelect');
// 默认选中第一个选项
select.selectedIndex = 0;
// 为选项添加事件监听器
select.addEventListener('change', () => {
// 获取当前选中的选项
const selectedOption = select.options[select.selectedIndex];
// 将所有选项的样式设为默认值
for (let i = 0; i < select.options.length; i++) {
select.options[i].style.fontWeight = 'normal';
}
// 将当前选中的选项样式设为不同的值
selectedOption.style.fontWeight = 'bold';
});
// 可以通过以下代码实现上一个和下一个选中某个元素
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
prevBtn.addEventListener('click', () => {
// 获取当前选中的选项索引
const currentIndex = select.selectedIndex;
if (currentIndex > 0) {
// 将当前选中的选项样式设为默认值
select.options[currentIndex].style.fontWeight = 'normal';
// 将上一个选项设为选中状态
select.options[currentIndex - 1].selected = true;
select.options[currentIndex - 1].style.fontWeight = 'bold';
}
});
nextBtn.addEventListener('click', () => {
// 获取当前选中的选项索引
const currentIndex = select.selectedIndex;
if (currentIndex < select.options.length - 1) {
// 将当前选中的选项样式设为默认值
select.options[currentIndex].style.fontWeight = 'normal';
// 将下一个选项设为选中状态
select.options[currentIndex + 1].selected = true;
select.options[currentIndex + 1].style.fontWeight = 'bold';
}
});
```
需要注意的是,上下选中元素的功能需要在HTML中添加两个按钮 `prevBtn` 和 `nextBtn`,并且需要对其添加事件监听器。