原生实现轮播图效果
style部分
<style>
*{margin:0; padding:0;}
li{list-style: none;}
.banner_wrap{
width:590px;
height: 470px;
border: 1px solid #000;
margin: 50px auto;
position: relative;
}
.banner{
width:590px;
height: 470px;
overflow: scroll;
}
.banner ul{
width:6000px;
overflow: hidden;
/* transition: all 0.3s linear; */
}
.banner li{
width:590px;
height: 470px;
float: left;
}
.banner li img{
width:590px;
height: 470px;
}
.page{
width: 100%;
position: absolute;
left: 0;
bottom: 20px;
text-align: center;
}
.page span{
display: inline-block;
width: 30px;
height: 30px;
background: #ccc;
line-height: 30px;
text-align: center;
margin-right:10px;
border-radius: 50%;
}
.page span.select{
background: red;
}
.btn_left,.btn_right{
width: 40px;
height: 80px;
line-height: 80px;
text-align: center;
position: absolute;
top: 50%;
margin-top: -40px;
background: rgba(0,0,0,0.5);
color: #fff;
font-size: 20px;
/* display: none; */
}
.btn_left{
left:0;
}
.btn_right{
right:0;
}
</style>
body部分 (注意:图片自己更换)
<div class="banner_wrap" id="banner_wrap">
<div class="banner" id="banner">
<ul>
<li><img src="image/banner8.jpg" alt=""></li>
<li><img src="image/banner1.jpg" alt=""></li>
<li><img src="image/banner2.jpg" alt=""></li>
<li><img src="image/banner3.jpg" alt=""></li>
<li><img src="image/banner4.jpg" alt=""></li>
<li><img src="image/banner5.jpg" alt=""></li>
<li><img src="image/banner6.jpg" alt=""></li>
<li><img src="image/banner7.jpg" alt=""></li>
<li><img src="image/banner8.jpg" alt=""></li>
<li><img src="image/banner1.jpg" alt=""></li>
</ul>
</div>
<div id="page" class="page">
<span class="select">1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
</div>
<p id="btn_left" class="btn_left"> < </p>
<p id="btn_right" class="btn_right"> > </p>
</div>
js部分
<script>
var banner=document.querySelector('#banner ul');
var bannerLi=document.querySelectorAll("#banner ul li");
var pages=document.querySelectorAll('#page span');
var imgs=document.querySelectorAll('#banner ul li img');
var btn_left=document.querySelector('#btn_left');
var btn_right=document.querySelector('#btn_right');
var banner_wrap=document.querySelector('#banner_wrap');
var imgW=imgs[0].offsetWidth; // 获取每一张图片的宽度
var timer=null;
// 默认是在代码中写的第一张图片显示(此时下标为0的图片是第八张图)
var num=1; // 控制每张图片的下标
banner.style.marginLeft=-imgW+'px';
btn_right.onclick=function(){
for(var i=0;i<pages.length;i++){
pages[i].className="";
}
banner.style.transition="all linear 0.3s"
num++;
// num最大到 bannerLi.length-1
if(num>=bannerLi.length-1){
num=bannerLi.length-1;
}
// 临界切换
if(num==bannerLi.length-1){
setTimeout(function(){
banner.style.transition=""
banner.style.marginLeft=-imgW*1+'px';
num=1;
// alert(123);
},300);
pages[0].className="select";
}else{
pages[num-1].className="select";
}
banner.style.marginLeft=-imgW*num+'px';
console.log(num);
console.log(123);
}
</script>