无限循环轮播图之JS部分(原生JS)

时间:2024-12-06 18:36:26

JS逻辑与框架调用,

 <script type="text/javascript">
var oBox = document.getElementById('box');
var oPrev = document.getElementById('prev');
var oNext = document.getElementById('next');
var oUl = oBox.children[0];
var aLi = oUl.children;
var aBtn = document.getElementById('btn').children; aLi[0].style.left = 0;//把第一张图片设置当前位置
var iNow = 0;
      
        //下一张
oNext.onclick = function(){
move(aLi[iNow],{left:-400});//当前图片向左运动 iNow++;
if (iNow == aLi.length) {
iNow = 0;
}
aLi[iNow].style.left = 400+'px';//下一张在右边准备
move(aLi[iNow],{left:0});//运动到当前位置 tab()
}
    // 上一张
oPrev.onclick = function(){
move(aLi[iNow],{left:400})
iNow--;
if (iNow < 0) {
iNow = aLi.length-1;
}
aLi[iNow].style.left = -400+'px';
move(aLi[iNow],{left:0}) tab()
}
    // 点击按钮
for(var i = 0 ;i < aBtn.length ; i++){
(function(index){
aBtn[i].onclick = function(){
if (index == iNow) {
return;
}else if (index < iNow ) { //点击的按钮在当前位置的左边
move(aLi[iNow],{left:400}); aLi[index].style.left = -400+'px';
move(aLi[index],{left:0})
}else if (index > iNow) {//点击的按钮在当前位置的右边
move(aLi[iNow],{left:-400})
aLi[index].style.left = 400+'px';
move(aLi[index],{left:0})
}
iNow = index
tab();
}
})(i);
}      // 为按钮添加样式
function tab(){
for (var i = 0; i < aBtn.length; i++) {
aBtn[i].className ='';
}
aBtn[iNow].className = 'on';
}
</script>