<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
.wrap{
width: 400px;
height: 300px;
border:1px solid #000;
margin:0 auto;
position: relative;
overflow: hidden;
}
.inner-wrap{
width: 2000px;
position: absolute;
}
.inner-wrap img{
width: 400px;
float: left;
height: 300px;
}
input{
outline: none;
position: absolute;
top:45%;
width: 50px;
height: 50px;
border-radius: 25px;
border:none;
background-color: #E8F2FB;
font-size: 24px;
}
.menu-button{
position: absolute;
bottom:10%;
left:35%;
}
.menu-button span{
width: 40px;
height: 40px;
border-radius: 20px;
background-color: #E8F2FB;
border:1px solid #ccc;
display: block;
float:left;
}
.menu-button .currentBtn{background-color: orange;}
#pre{left:5%;}
#next{right:5%;}
</style>
<meta charset="UTF-8">
<title>Bnner</title>
</head>
<body>
<div class="wrap" id="wrap">
<div class="inner-wrap" style="left:-400px" id="inner-wrap">
<img src="images/3.jpg" alt="">
<img src="images/1.jpg" alt="">
<img src="images/2.jpg" alt="">
<img src="images/3.jpg" alt="">
<img src="images/1.jpg" alt="">
</div>
<input type="button" id="pre" value="<">
<input type="button" id="next" value=">">
<div class="menu-button" id="menu-button">
<span index="0" class="currentBtn"></span>
<span index="1"></span>
<span index="2"></span>
</div>
</div>
</body>
<script type="text/javascript">
window.οnlοad=function(){
var prevBtn=document.getElementById('pre');
var nextBtn=document.getElementById('next');
var oWrap=document.getElementById('wrap');
var container=document.getElementById('inner-wrap');
var buttonsList=document.getElementById('menu-button');
var aCurrentButton=buttonsList.getElementsByTagName('span');
var timer=null;
var index=0;
function animate(offset){
var newLeft=parseInt(container.style.left)+offset;
console.log(newLeft);
if(newLeft>-400){container.style.left=-1200+'px';}
else if(newLeft<-1600){container.style.left=-800+'px';}
else{container.style.left=newLeft+'px'}
}
prevBtn.οnclick=function(){
index+=1;
if(index>2){
index=0;
}
buttonColor();
animate(-400);
}
nextBtn.οnclick=function(){
index-=1;
if(index<0){
index=2;
}
buttonColor();
animate(400);
}
// 自动播放
function play(){
timer=setInterval(function(){
prevBtn.onclick();
},150)
}
play();
function stop(){
clearInterval(timer);
}
oWrap.οnmοuseοver=stop;
oWrap.οnmοuseοut=play;
// 当前按钮颜色
function buttonColor(){
for (var i= 0;i<aCurrentButton.length;i++) {
aCurrentButton[i].className='';
}
aCurrentButton[index].className='currentBtn';
}
// 自动播放时按钮的颜色
for(var i=0;i<aCurrentButton.length;i++)
{
(function(j){
aCurrentButton[i].οnclick=function(){
var oCurrentIndex=parseInt(this.getAttribute('index'));
index=oCurrentIndex;
offset=-400*(oCurrentIndex-1);
animate(offset);
buttonColor();
}
})(i)
}
}
</script>
</html>
原生js轮播图
最新推荐文章于 2023-05-22 19:10:49 发布