一、利用JQuery
html代码
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
css代码
ul {
width: 400px;
}
li {
width: 100%;
height: 80px;
border: 1px solid #000;
}
.active {
background: red;
}
首先引入JQuery CDN
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
js代码
$('li').click(function(){
$(this).siblings().removeClass('active');
$(this).addClass('active');
})
二、Vue中(v-for数据时)
相信大家都会遇到这种情况:v-for循环时,我只需要点击到的元素做出相应反应,其他的元素不变;但是往往所有v-for循环出的元素都会变化。如下面的代码:我需要点击到的元素添加一个类样式,其他元素不变,但是这样会导致所有的元素都会变化
解决方法:使用index索引,当点击一个元素时,将该元素的index索引赋给类样式的启用变量,如果该变量和index相等时,则启用该类样式
html:
< div v-for = "(item,index) in items" :class = "isactive == index ? 'addclass' : '' " @click='onclick(index)'>
< span>{{item.name}}< /span>
< /div>
css:
.addclass{
color : red;
}
js:
data:{
items :[
{
name:'apple',
price: '5'
},
{
name:'banana',
price:"3"
},
{
name:'pear',
price:'4'
}
],
isactive : -1
}
onclick(index){
//将点击的元素的索引赋值给bian变量
this.isactive = index
}