1. 程式人生 > 其它 >js 製作輪播圖 並且可以通過按鈕定位到拿一張圖片,上一張下一張

js 製作輪播圖 並且可以通過按鈕定位到拿一張圖片,上一張下一張

<div id="bannerimg">
<div id="hreff">
<button >1</button>
<button >2</button>
<button >3</button>
<button >4</button>

</div>

<div id="ss" style="margin-left: 0;">
<div id="bannerimgone">
<img src="img/1%20(1).jpg" >
</div>
<div id="bannerimgone">
<img src="img/4.jpg" >
</div>
<div id="bannerimgone">
<img src="img/1%20(3).jpg" >
</div>
<div id="bannerimgone">
<img src="img/1%20(1).gif" >
</div>
</div>
</div>
<div id="href">
<a href="javascript:;" id="pre" class="arrow" style="text-decoration: none; ">&lt;</a>
<a href="javascript:;" id="next" class="arrow" style="text-decoration: none;margin-left: 470px;" >&gt;</a>
</div>

<script type="text/javascript">
// 獲取頁面上包裹照片DIV的元素
var img=document.getElementById("ss")

var pre=document.getElementById("pre")
var next=document.getElementById("next")
var index=0;//宣告一個全域性變數
var oneonly;//全域性宣告計時器
var div=document.getElementById("bannerimg")//獲取元素節點

var hreff=document.getElementById("hreff").getElementsByTagName("button")

console.log(hreff)




function ma(){
// 每次呼叫這個方法的時候index+1 因為頁面上有四個圖片第三次的時候就已經到第四章圖片的位置
index++;
// 判斷如果 index++大於3的時候超過了我們設定的圖片數量 就等於0從新迴圈
if(index>3){
index=0
}
co()
// 如果 值等於1500px就是四張圖 就改成0px
if(img.style.marginLeft=="-1500px"){
img.style.marginLeft="0px"

}else{
img.style.cssText="margin-left: -"+index*500+"px;"
}

}
for (let i = 0 ;i<hreff.length; i++){
hreff[i].onclick=function(){
index=i;
img.style.cssText="margin-left: -"+index*500+"px;"
co()

}
}


function co(){
for(let y=0;y<hreff.length;y++){
hreff[y].style.backgroundColor=""

}
hreff[index].style.backgroundColor="lawngreen"


}



pre.onclick=function(){
index--;
// 上一張 index-- 第一次執行的時候i--第一張圖片的下標是-1 之後執行下面的迴圈 如果小於0 就從新賦值為3
if(index<0){
index=3
}

if(img.style.marginLeft=="0px"){
img.style.marginLeft="-1500px"

}else{
img.style.cssText="margin-left: -"+index*500+"px;"


}
}
next.onclick=function(){
index++;
if(index>3){
index=0
}
if(img.style.marginLeft=="-1500px"){
img.style.marginLeft="0px"

}else{
img.style.cssText="margin-left: -"+index*500+"px;"
}



}




function start(){//定時器 用來下面清除
oneonly=setInterval(function(){
ma()

},2000);
}
start();
function stop(){
clearInterval(oneonly);//清除計時器
}

div.onmouseleave = start; //計時器開始
div.onmouseenter = stop; //計時器結束
</script>