1. 程式人生 > >用原生JS實現 圖片輪播切換 功能

用原生JS實現 圖片輪播切換 功能

效果如圖:


程式碼如下:

<!DOCTYPE HTML>
<html>


<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>點點點切換</title>
<style>
ul {
padding: 0;
margin: 0;
}

li {
list-style: none;
}

body {
background: #333;
}

.pic {
width: 400px;
height: 500px;
position: relative;
margin: 0 auto;
background: url(img/loader_ico.gif) no-repeat center #fff;
}

.pic img {
width: 400px;
height: 500px;
}

.pic ul {
width: 40px;
position: absolute;
top: 0;
right: -50px;
}

.pic li {
width: 40px;
height: 40px;
margin-bottom: 4px;
background: #666;
}

.pic .active {
background: #FC3;
}

.pic span {
top: 0;
}

.pic p {
bottom: 0;
margin: 0;
}

.pic p,
.pic span {
position: absolute;
left: 0;
width: 400px;
height: 30px;
line-height: 30px;
text-align: center;
color: #fff;
background: #000;
}

.btn {
width: 24px;
height: 24px;
background: rgba(0, 0, 0, 0.5);
position: absolute;
top: 250px;
text-align: center;
line-height: 24px;
text-decoration: none;
color: #fff;
}

.pic .next {
right: 0;
}
</style>


</head>


<body>


<div id="pic" class="pic">
<img src="" />
<span>數量正在載入中……</span>
<p>文字說明正在載入中……</p>
<ul></ul>
<a href="javascript:;" class="btn next">></a>
<a href="javascript:;" class="btn prev"><</a>
</div>


<script>

var oDiv=document.getElementById("pic")
var oImg=oDiv.getElementsByTagName("img")[0]
var oSpan=oDiv.getElementsByTagName("span")[0]
var oP=oDiv.getElementsByTagName("p")[0]
var oUl=oDiv.getElementsByTagName("ul")[0]
var oLi=oUl.getElementsByTagName("li")
var oA=oDiv.getElementsByTagName("a")

/*定義陣列begin*/
var num=0
var arrImg=["img/1.png","img/2.png","img/3.png","img/4.png"]
var arrTex=["圖片1","圖片2","圖片3","圖片4"]
/*定義陣列end*/

/*初始化展示begin*/
oImg.src=arrImg[0]
oSpan.innerHTML=(num+1)+"/"+arrImg.length
oP.innerHTML=arrTex[0]
/*初始化展示end*/

/*點選下一張切換begin*/
oA[0].onclick=function(){
num++
if(num>arrImg.length-1){
num=0
}
oImg.src=arrImg[num]
oSpan.innerHTML=(num+1)+"/"+arrImg.length
oP.innerHTML=arrTex[num]
for (var i=0;i<oLi.length;i++) {
oLi[i].className=""
}
oLi[num].className="active"

}
/*點選下一張切換end*/

/*點選上一張切換begin*/
oA[1].onclick=function(){
num--
if(num<0){
num=arrImg.length-1
}
oImg.src=arrImg[num]
oSpan.innerHTML=(num+1)+"/"+arrImg.length
oP.innerHTML=arrTex[num]
for (var i=0;i<oLi.length;i++) {
oLi[i].className=""
}
oLi[num].className="active"

}
/*點選下一張切換end*/


/*for迴圈拼接生成li begin*/
for ( var i=0;i<arrImg.length;i++) {
oUl.innerHTML+="<li></li>"
}
/*for迴圈拼接生成li end*/

oLi[0].className="active"

/*點選當前li關聯圖片下標 begin*/
for ( var i=0;i<oLi.length;i++) {
oLi[i].index=i
oLi[i].onclick=function(){
for ( var i=0;i<oLi.length;i++) {

oLi[i].className=""
}

this.className="active"
num=this.index
oImg.src=arrImg[num]
oSpan.innerHTML=(num+1)+"/"+arrImg.length
oP.innerHTML=arrTex[num]

}

}
/*點選當前li關聯圖片下標 begin*/


 
</script>
</body>


</html>