我相信大家一定有过这样的体验,就是在我们打开一个导航栏,在我们进行点击的时候,会在其加上背景,同时对其同级的属性自动去除背景,体验起来是相当的舒服。今天我们就来简单制作一下吧!css代码:
<style>
.top {
margin:1em 0 1em 3em;
padding-bottom:2em;
}
.left_box {
border: solid 1px #DDD;
width: 122px;
height: 30px;
line-height: 30px;
text-align: center;
font-weight: bold;
font-size: 16px;
cursor: pointer;
float: left;
}
.right_box {
border: solid 1px #DDD;
border-left: none;
width: 122px;
height: 30px;
line-height: 30px;
text-align: center;
font-weight: bold;
font-size: 16px;
cursor: pointer;
float: left;
}
.hover {
background: #009688;
color:#fff;
}
</style>
Html代码:
<div class="top">
<div class="left_box hover" onclick="bg_change(this)">盒码</div>
<div class="right_box" onclick="bg_change(this)">箱码</div>
<div class="right_box" onclick="bg_change(this)">板码</div>
<div class="right_box" onclick="bg_change(this)">标签</div>
</div>
js代码,这里需要注意:直接使用Jquery属性 ( t h i s ) 的 话 , 在 某 些 情 况 下 并 不 生 效 , 故 而 在 o n c l i c k 事 件 中 , 加 上 t h i s 属 性 , 即 : b g c h a n g e ( t h i s ) , 这 样 的 话 , J q u e r y 就 可 以 准 确 匹 配 到 你 (this)的话,在某些情况下并不生效,故而在onclick事件中,加上this属性,即:bg_change(this),这样的话,Jquery就可以准确匹配到你 (this)的话,在某些情况下并不生效,故而在onclick事件中,加上this属性,即:bgchange(this),这样的话,Jquery就可以准确匹配到你(this)所指定的容器了!
<script>
function bg_change(e) {
$(e).addClass("hover");
$(e).siblings().each(function (i) {
$(this).removeClass("hover");
});
}
</script>
最终效果: