原生js实现轮播

时间:2021-09-04 16:04:20
<!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" alt="">
<img src="img/f2.jpg" alt="">
<img src="img/f3.jpg" alt="">
</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>