js实现轮播图案例
<style>
* {margin:0; padding:0; list-style:none;}
.box {width:850px; height:500px; margin:50px auto; overflow:hidden; position:relative;}
.box ul {position:absolute;left: 0;top: 0;}
.box ul li{height:500px;float: left;}
.box ol {position:absolute;right: 10%;bottom: 10px;z-index:6}
.box ol li{width: 20px;height: 20px;background: #fff;margin-left: 5px;float: left;line-height: 20px;text-align: center;cursor: pointer;}
.box ol li.ac{background: red;color: #fff;}
.box>a{text-decoration: none;position: absolute;top: 50%;margin-top: -10px;height: 40px;line-height: 32px;text-align: center;width: 40px;font-size: 40px;vertical-align: middle;color: #fff;background: rgba(0,0,0,0.5);z-index:6;}
#goPrev{left: 0;}
#goNext{right: 0;}
img{width:850px; height:500px;}
</style>
<-- move方法请看博主上篇博客 -->
<script src="move.js"></script>
<body>
<div class="box">
<ul>
<li><img src="images/1.jpg" /></li>
<li><img src="images/2.jpg" /></li>
<li><img src="images/3.jpg" /></li>
<li><img src="images/4.jpg" /></li>
<li><img src="images/5.jpg" /></li>
</ul>
<ol></ol>
<a href="javascript:;" id="goPrev">«</a>
<a href="javascript:;" id="goNext">»</a>
</div>
<script>
window.onload = function(){
var box = document.querySelector('.box'),
ol = document.querySelector('.box ol'),
ul = document.querySelector('.box ul'),
imgs = ul.querySelectorAll('li'),
goPrev = document.querySelector('#goPrev'),
goNext = document.querySelector('#goNext'),
btns = ol.children,
len = imgs.length
var index = 0
var lastIndex = 0
var width = imgs[0].offsetWidth
var isMove = false
for(var i = 0; i < len; i++){
var li = document.createElement('li')
if(i === 0) li.className = 'ac'
li.innerHTML = i+1
ol.appendChild(li)
}
ul.appendChild(imgs[0].cloneNode(true))
ul.style.width = width*(len+1) + 'px'
Array.from(btns).forEach(function(btn, i){
btn.onclick = function(){
if(!isMove){
isMove = true
lastIndex = index
index = i
btns[lastIndex].classList.remove('ac')
btns[index].classList.add('ac')
utils.move1(ul, 'left', -index * width, () =>{
isMove = false
})
}
}
})
goNext.onclick = function(){
//判断静止状态 ,静止状态点击才有效,只有静止才可以进入if,进入if就可以运动了
// isMove改为true
if(!isMove){
isMove = true
lastIndex = index
index++
if(index === len) {
index = 0
utils.move1(ul, 'left', -len * width, () =>{
isMove = false
ul.style.left = '0px'
})
} else{
utils.move1(ul, 'left', -index * width,() =>{
isMove = false
})
}
btns[lastIndex].classList.remove('ac')
btns[index].classList.add('ac')
}
}
goPrev.onclick = function(){
if(!isMove){
isMove = true
lastIndex = index
index--
if(index < 0){
index = len-1
ul.style.left = -len*width + 'px'
}
utils.move1(ul, 'left', -index * width, () =>{
isMove = false
})
btns[lastIndex].classList.remove('ac')
btns[index].classList.add('ac')
}
}
var timer = setInterval(goNext.onclick,1000)
box.onmouseenter = function(){
clearInterval(timer)
}
box.onmouseleave = function(){
timer = setInterval(goNext.onclick,1000)
}
}
</script>
</body>