選項卡切換效果,點選切換圖片
阿新 • • 發佈:2018-12-23
今天分享一篇前端開發實戰當中經常使用到的選項卡切換效果的文章,希望對您有所幫助,歡迎留言探討。
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>