例一: JQuery
效果:
JS:
$(function () {
//遍历list(一般为ul li)
$("#menu a").each(function () {
//给当前项添加点击事件(点击后切换样式)
$(this).bind('click',function () {
// 移除其他所有项的active类
$("#menu a").each(function () {
$(this).removeClass('active');
})
// 给当前项添加active类
$(this).addClass('active');
})
});
})
css:
.active{
background-color: yellow; /* 高亮颜色,可以根据需要修改 */
}
例二: Vue
<div id="app">
<ul>
<li v-for="(item, index) in items"
:key="index"
:class="{ 'active': selectedIndex === index }"
@click="selectItem(index)">
{
{ item }}
</li>
</ul>
</div>
JS:
new Vue({
el: '#app',
data: {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4'],
selectedIndex: null // 初始没有选中的项
},
methods: {
selectItem(index) {
this.selectedIndex = index; // 设置当前选中的索引
}
}
});
css:
.active{
background-color: yellow; /* 高亮颜色,可以根据需要修改 */
}