1.通过addClass,removeClass,toggleClass属性实现如下案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>样式操作</title>
<style>
.hello{
width: 300px;
height: 300px;
border: 1px solid green;
background-color: chartreuse;
}
</style>
<script src="../js/jquery-3.3.1.min.js"></script>
</head>
<body>
<div>
明月几时有,把酒问青天。不知天上宫阙,今夕是何年!
</div>
<input type="button" value="变身" id="btn1">
<input type="button" value="还原" id="btn2">
<input type="button" value="切换" id="btn3">
</body>
<script>
//添加class属性hello
$("#btn1").click(function () {
$("div").addClass("hello")
})
//移除class属性hello
$("#btn2").click(function () {
$("div").removeClass("hello")
})
//如果有class hello属性 我就移除 没有就添加
$("#btn3").click(function () {
$("div").toggleClass("hello")
})
</script>
</html>
2.1.通过addClass,removeClass属性实现tab栏切换
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
.wrapper {
width: 1000px;
height: 475px;
margin: 0 auto;
margin-top: 100px;
}
.tab {
border: 1px solid #ddd;
border-bottom: 0;
height: 36px;
width: 320px;
}
.tab li {
position: relative;
float: left;
width: 80px;
height: 34px;
line-height: 34px;
text-align: center;
cursor: pointer;
border-top: 4px solid #fff;
}
.tab span {
position: absolute;
right: 0;
top: 10px;
background: #ddd;
width: 1px;
height: 14px;
overflow: hidden;
}
.products {
width: 1002px;
border: 1px solid #ddd;
height: 476px;
}
.products .main {
float: left;
display: none;
}
.products .main.selected {
display: block;
}
.tab li.active {
border-color: red;
border-bottom: 0;
}
</style>
<script src="../js/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="wrapper">
<ul class="tab">
<li class="tab-item active">国际大牌<span>◆</span></li>
<li class="tab-item">国妆名牌<span>◆</span></li>
<li class="tab-item">清洁用品<span>◆</span></li>
<li class="tab-item">男士精品</li>
</ul>
<div class="products">
<div class="main selected">
<a href="###"><img src="images/guojidapai.jpg" alt=""/></a>
</div>
<div class="main">
<a href="###"><img src="images/guozhuangmingpin.jpg" alt=""/></a>
</div>
<div class="main">
<a href="###"><img src="images/qingjieyongpin.jpg" alt=""/></a>
</div>
<div class="main">
<a href="###"><img src="images/nanshijingpin.jpg" alt=""/></a>
</div>
</div>
</div>
<script>
//获取所有.tab-item列表 绑定鼠标移入时间
$(".tab-item").mouseover(function () {
//给当前移入的li列表添加active class属性 除他之外的li 列表移除active class属性
$(this).addClass("active").siblings().removeClass("active")
//获取所有的main class属性等于当前的索引下标 添加selected class属性 除他之外的main class移除selected class属性
$(".main").eq($(this).index()).addClass("selected").siblings().removeClass("selected")
})
</script>
</body>
</html>