【轮播图js实现】


// 获取元素
/* 我就是个憨批!!! */
let box = document.getElementsByClassName('box')[0];
let main = document.getElementsByClassName('main');
let imgs = document.querySelectorAll('.main > img')
let last = document.querySelector('.last')
let next = document.querySelector('.next')
let nums = document.querySelectorAll('.circle > ol > li')

// 初始化变量
let index = 0;
let timer;

play()

// 自动播放
function play(){
    timer = setInterval(autoPlay, 2000);
}

// 停止自动播放
box.onmouseover = function () { 
    clearInterval(timer);
}


// 开启自动播放
box.onmouseleave = function () {  
    timer = setInterval(autoPlay, 2000);
}

// next
next.onclick = function(){
    let classIndex;
    imgs.forEach((item, id) => {
        if(item.className){
            classIndex = id;
        }
    })
    if(classIndex < imgs.length-1){
        changePic(classIndex + 1)
    }else {
        classIndex = 0;
        changePic(classIndex)
    }
}

// last
last.onclick = function(){
    let classIndex;
    imgs.forEach((item, id) => {
        if(item.className){
            classIndex = id;
        }
    })
    if(classIndex > 0){
        changePic(classIndex - 1)
    }else {
        classIndex = imgs.length - 1;
        changePic(classIndex)
    }
}

// 遍历所有数字导航实现划过切换至对应图片
for(let i = 0; i < nums.length; i ++){
    nums[i].onclick = function(){
        changePic(i)
    }
}


// 自动播放函数
function autoPlay(){
    if(++index >= imgs.length){
        index = 0;
    }
    changePic(index)
}

// 定义图片切换函数
function changePic(curIndex) {
    for(let i = 0; i < imgs.length; i ++){
        imgs[i].className = '';
        nums[i].className = '';
    }
    imgs[curIndex].className = 'current';
    nums[curIndex].className = 'current'
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值