今天分享一篇前端开发实战当中经常使用到的选项卡切换效果的文章,希望对您有所帮助,欢迎留言探讨。
1、html结构布局:
<div id="box">
<div class="img">
<ul>
<li class="active"><img src="img/1.jpg" /></li>
<li><img src="img/2.jpg" /></li>
<li><img src="img/3.jpg" /></li>
<li><img src="img/4.jpg" /></li>
</ul>
<p><span id="index">1</span>/4</p>
</div>
<div class="btn">
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
</div>
2、css布局样式:
<style>
*{ margin:0; padding:0; font-family:"Microsoft yahei",serif;}
li{ list-style-type: none;}
#box{
position: relative;
width: 350px;
height: 580px;
margin: 50px auto;
}
#box .img{
position: absolute;
top: 0;
left: 0;
width: 326px;
height: 580px;
}
#box .img li{
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
#box .img li.active{
display: block;
}
#box .img li img{
display: block;
}
#box .img p{
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 35px;
text-align: center;
background: rgba(0,0,0,.5);
color: #fff;
font-size: 14px;
font-weight: bold;
line-height: 35px;
}
#box .btn{
position: absolute;
top: 0;
right: 0;
}
#box .btn ul li{
width: 24px;
height: 24px;
margin-bottom: 10px;
line-height: 24px;
color: #fff;
font-weight: bold;
font-size: 12px;
text-align: center;
background: #000;
cursor: pointer;
}
#box .btn ul li.active{
background: #f60;
}
</style>
3、js行为实现:
<script>
var aBtn = document.getElementsByClassName("btn")[0].getElementsByTagName("li"),
aImg = document.getElementsByClassName("img")[0].getElementsByTagName("li"),
oTxt = document.getElementById("index"),
length = aBtn.length,
index = 0;//这个变量用来存储当前显示的序号
for (var i = 0; i < length; i++)
{
aBtn[i].goudan = i;//自定义属性,用来存每个人的序号
aBtn[i].onclick = function () {
if ( this.goudan !== index ){
aBtn[index].className = "";//把前一个的名字去掉
aImg[index].className = "";//把前一图片的名字去掉
index = this.goudan;//把序号变成当前点击的这个的序号
aBtn[index].className = "active";//给点击的这个加名字
aImg[index].className = "active";//给当前要显示的图片加名字
oTxt.innerHTML = index+1;
}
};
}
</script>