实现轮播图透明度切换+自动走
style部分
<style>
li{list-style: none;}
*{margin:0; padding:0;}
.banner{
width: 590px;
height: 470px;
margin: 50px auto;
border: 2px solid green;
position: relative;
}
.banner li{
width: 590px;
height: 470px;
position: absolute;
left: 0;
top: 0;
opacity: 0;
transition: opacity 1s linear;
}
.banner li:nth-of-type(1){
opacity: 1;
}
.banner li img{
width: 590px;
height: 470px;
}
#page{
position: absolute;
left: 30px;
bottom: 20px;
overflow: hidden;
}
#page span{
float: left;
width: 20px;
height: 20px;
border-radius: 50%;
background: #ccc;
font-size: 12px;
line-height: 20px;
text-align: center;
margin:0 4px;
}
#page span:nth-of-type(1){
background: red;
}
#btn_left{
width: 40px;
height: 60px;
position: absolute;
top: 50%;
margin-top: -30px;
left: 0;
background: rgba(0,0,0,0.5);
color: #fff;
text-align: center;
line-height: 60px;
}
#btn_right{
width: 40px;
height: 60px;
position: absolute;
top: 50%;
margin-top: -30px;
right: 0;
background: rgba(0,0,0,0.5);
color: #fff;
text-align: center;
line-height: 60px;
}
</style>
body部分 (注意:图片自己更换)
<div class="banner">
<ul id="banner_img">
<li>
<a href="#">
<img src="image/banner1.jpg" alt="">
</a>
</li>
<li>
<a href="#">
<img src="image/banner2.jpg" alt="">
</a>
</li>
<li>
<a href="#">
<img src="image/banner3.jpg" alt="">
</a>
</li>
<li>
<a href="#">
<img src="image/banner4.jpg" alt="">
</a>
</li>
<li>
<a href="#">
<img src="image/banner5.jpg" alt="">
</a>
</li>
<li>
<a href="#">
<img src="image/banner6.jpg" alt="">
</a>
</li>
<li>
<a href="#">
<img src="image/banner7.jpg" alt="">
</a>
</li>
<li>
<a href="#">
<img src="image/banner8.jpg" alt="">
</a>
</li>
</ul>
<p id="btn_left">左</p>
<p id="btn_right">右</p>
<div id="page">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
</div>
</div>
js部分
<script>
var imgs=document.querySelectorAll('#banner_img li');
var btn_left=document.querySelector('#btn_left');
var btn_right=document.querySelector('#btn_right');
var pages=document.querySelectorAll('#page span');
var num=0;
var timer=null;
function reset(){
for(var i=0;i<imgs.length;i++){
imgs[i].style.opacity=0;
pages[i].style.background="#ccc";
}
}
btn_right.onclick=function(){
clearInterval(timer);
reset();
num++;
if(num>imgs.length-1){
num=0
}
imgs[num].style.opacity=1;
pages[num].style.background="red";
console.log(num);
automove();
}
btn_left.onclick=function(){
clearInterval(timer);
reset();
num--;
if(num<0){
num=imgs.length-1;
}
imgs[num].style.opacity=1;
pages[num].style.background="red";
console.log(num);
automove();
}
for(var i=0;i<pages.length;i++){
pages[i].index=i;
pages[i].onclick=function(){
clearInterval(timer);
reset();
this.style.background="red";
imgs[this.index].style.opacity=1;
num=this.index;
automove();
}
}
function automove(){
timer=setInterval(function(){
reset();
num++;
if(num>imgs.length-1){
num=0
}
imgs[num].style.opacity=1;
pages[num].style.background="red";
},2000)
}
automove();
</script>
希望可以帮到大家