1. 程式人生 > >原生js實現輪播

原生js實現輪播

tex tom enter utf-8 定義 radi absolut tco query

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.container{
width: 500px;
height: 300px;
position: relative;
border: 1px solid red;
}
.img-content{
width: 500px;
height: 300px;
}
.point{
position: absolute;
left: 30%;
bottom: 5%;
list-style: none;
}
.point>li{
width: 20px;
height: 20px;
float: left;
margin-left: 10px;
border: 1px solid red;
border-radius: 50%;
line-height: 20px;
text-align: center;
}
.left{
width: 50px;
height: 30px;
position: absolute;
top: 40%;
left: 10%;
border: 1px solid red;
}
.right{
width: 50px;
height: 30px;
position: absolute;
top: 40%;
right: 10%;
border: 1px solid red;
}
.img-content>img{
display: none;
}
.img-content>img:nth-child(1){
display: inline-block;
}
</style>
</head>
<body>
<div class="container">
<div class="img-content">
<img src="img/f1.jpg" >
<img src="img/f2.jpg" >
<img src="img/f3.jpg" >
</div>
<ul class="point">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<div class="left">
<
</div>
<div class="right">
>
</div>
</div>
<script>
/*獲取dom元素*/
var img=document.querySelectorAll(".img-content>img");
var li=document.querySelectorAll(".point>li");
var left=document.getElementsByClassName("left")[0];
var right=document.getElementsByClassName("right")[0];
var container=document.getElementsByClassName("container")[0];
var index=0;
var timer=setInterval(slide,2000);//定義一個計時器
function slide(){
for(var i=0;i<img.length;i++){
img[i].style.display="none";//先將所有的圖片都隱藏
}
img[index].style.display="inline-block";//再顯示其中一張
index++;
if(index==img.length){
index=0;//當顯示到最後一張時,在回到第一張
}
}
container.onmouseover=function(){
clearInterval(timer);//清楚計時器
};
container.onmouseout=function(){
timer=setInterval(slide,2000);//再次啟用計時器,記住此處一定不要再用var
};
var arr=[];//定義一個數組
for(var i=0;i<li.length;i++){
arr.push(li[i]);//將每個添加到數組內
li[i].addEventListener("click",function(){//利用循環給每個li綁定點擊事件
var index1=arr.indexOf(this);//獲取當前點擊事件的對象也就是this在arr中的下標,然後再顯示當前下標的圖片;
console.log(index1);
for(var j=0;j<img.length;j++){
img[j].style.display="none";//先用循環將每張圖片隱藏
}
img[index1].style.display="inline-block";//顯示這個下標的圖片
})
}
/*right.addEventListener("click", function () {
var arr1=[];
for(var i=0;i<img.length;i++){
//arr1.push(getComputedStyle(img[i])[‘display‘]);
if(getComputedStyle(img[i])[‘display‘]=="inline-block"){
img[i+1].style.display="inline-block";
if(i>=img.length){
img[0].style.display="inline-block";
}
}
}
console.log(arr1);
})*/
</script>
</body>
</html>

原生js實現輪播