原生JS实现轮播图效果
上篇文章我们说到了怎样利用原生JS实现Tab切换的效果,现在我们来说一下Tab切换的“升级版”。如何利用原生JS实现轮播图效果。如图:
HTML代码:
<div class="box">
<img src="img/0.jpg" alt="">
<!-- <img src="img/1.jpg" alt="">
<img src="img/2.jpg" alt="">
<img src="img/3.jpg" alt=""> -->
<div class="btn btn_l"> < </div>
<div class="btn btn_r"> > </div>
<ul class="points">
<li class="blue"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
CSS代码:
*{
margin: 0;
padding: 0;
list-style: none;
}
.box{
width: 500px;
height: 300px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
img{
width: 500px;
height: 300px;
}
.btn,.points{
position: absolute;
cursor: pointer;
}
.btn{
width: 20px;
height: 40px;
background: green;
color: white;
font-size: 20px;
text-align: center;
line-height: 40px;
top: 50%;
margin-top: -20px;
z-index: 999;
}
.btn_l{
left: 0;
}
.btn_r{
right: 0;
}
.points{
width: 100px;
height: 20px;
border-radius: 20px;
background: skyblue;
left: 50%;
margin-left: -50px;
bottom: 30px;
}
.points li{
width: 15px;
height: 15px;
border-radius: 50%;
background-color: red;
float: left;
margin: 2.5px 5px;
}
.points li.blue{
background: blue;
}
JS代码:
// 1.点击4个点 切换成对应的图片
// 2.点击左右按钮 图片切换
// 3.切换图片时 改变图片的src
// 4.左右按钮 和 下面四个点 需要控制同一个变量
// 1.获取元素
var oImg=document.getElementsByTagName("img")[0];
var oBtn_l=document.getElementsByClassName("btn_l")[0];
var oBtn_r=document.getElementsByClassName("btn_r")[0];
var aLi=document.getElementsByTagName("li");
// 2.声明全局变量
var index=0;
function point(){
for(var i=0;i<aLi.length;i++){
aLi[i].className="";
}
aLi[index].className="blue";
}
// 3.点击左按钮 index-- 0临界点
oBtn_l.onclick=function(){
// if(index==0){
// index=3;
// }else{
// index--;
// }
index==0?index=3:index--;
oImg.src="img/"+index+".jpg";
point();
}
// 4.点击右按钮 index++ 3临界点
oBtn_r.onclick=function(){
index==3?index=0:index++;
oImg.src="img/"+index+".jpg";
point();
}
// 5.下面4个点
for(var i=0;i<aLi.length;i++){
aLi[i].a=i;//给li添加 自定义的属性 储存 i
aLi[i].onclick=function(){
index=this.a;
oImg.src="img/"+index+".jpg";
point();
}
}
// aLi[0].οnclick=function(){
// index=0;
// oImg.src="img/"+index+".jpg";
// point();
// }
// aLi[1].οnclick=function(){
// index=1;
// oImg.src="img/"+index+".jpg";
// point();
// }
// aLi[2].οnclick=function(){
// index=2;
// oImg.src="img/"+index+".jpg";
// point();
// }
// aLi[3].οnclick=function(){
// index=3;
// oImg.src="img/"+index+".jpg";
// point();
// }
注意:写轮播图效果的时候需要注意一点,声明一个全局变量,使左右按钮,以及下边的几个切换点在点击时控制的是同一个变量在改变。
视频讲解链接:
https://www.bilibili.com/video/BV1L5411x7Ao/
转载:https://blog.csdn.net/qq_39155611/article/details/106424243
查看评论