原生JS实现无缝轮播图(完整代码)

代码案例仅供参考

html+css+js实现原生无缝轮播图,是js学习的必修课,首先看下本案例轮播图效果(轮播图片素材来源于YONEX官网)

lunbo


话不多说直接上代码,关键处都有注释

1.HTML部分

一般情况下img标签在class="swiper-img"盒子中根据需要的数量创建,小圆点则在class="swiper-active"的盒子中创建(这里使用的是ul),但为了方便减少之后需要修改轮播图数量时的操作,本案例使用JS对该部分结构进行动态渲染。(见JS部分)

    <div class="swiper-box">
        <div class="swiper-img"></div>
        <ul class="swiper-active"></ul>
        <!--左右箭头使用阿里图标库svg代码-->
        <div id="next">
            <svg t="1712474542494" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                p-id="1432">
                <!--可修改按钮初始颜色-->
                <path
                    d="M614.727053 511.42259l-403.237243-403.23724299a63.349415 63.349415 0 1 1 89.622481-89.62248201L749.160776 466.675274a63.349415 63.349415 0 0 1 0 89.494632L301.048367 1004.282315a63.349415 63.349415 0 1 1-89.49463301-89.622482L614.663128 511.42259z"
                    fill="#ccc" p-id="1433"></path>
            </svg>
        </div>
        <div id="prev">
            <svg t="1712474561555" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                p-id="1630">
                <!--可修改按钮初始颜色-->
                <path
                    d="M409.272947 512.57741l403.237243 403.23724299a63.349415 63.349415 0 1 1-89.622481 89.62248201L274.839224 557.324726a63.349415 63.349415 0 0 1 0-89.494632L722.951633 19.717685a63.349415 63.349415 0 1 1 89.49463301 89.622482L409.336872 512.57741z"
                    p-id="1631" fill="#ccc"></path>
            </svg>
        </div>
    </div>

2.CSS部分

css部分其实没啥好说的,根据自己的想法进行调整和修改

        * {
            margin: 0;
            padding: 0;
            list-style: none;
            border: 0;
        }
        /*当前为全屏轮播图,可自行调整轮播图盒子的宽高*/
        .swiper-box {
            position: relative;
            height: calc(100vh);
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: end;
            overflow: hidden;
        }
        .swiper-img {
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            z-index: -1;
            display: flex;
            flex-direction: row;
        }
        /*当前为全屏轮播图,可自行调整轮播图盒子的宽高*/
        .swiper-img img {
            width: calc(100vw);
            height: calc(100vh);
        }
        .swiper-active {
            height: 25px;
            margin-bottom: 20px;
            display: flex;
            flex-direction: row;
            align-items: center;
        }
        /*轮播图底部可选择小圆点或条形,自行修改*/
        /* 小圆点 */
        /* .swiper-active li {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #fff;
            margin: 0 8px;
            transition: all .5s;
            cursor: pointer;
            opacity: .4;
        }
        .swiper-active .active {
            width: 18px;
            height: 18px;
            opacity: 1;
        } */
        /* 长方形 */
        .swiper-active li {
            width: 40px;
            height: 8px;
            background: #fff;
            margin: 0 8px;
            transition: all .5s;
            cursor: pointer;
        }

        .swiper-active .active {
            background: rgb(51, 51, 250);
            opacity: 1;
        }
        #prev,
        #next {
            width: 70px;
            height: 100px;
            position: absolute;
            top: 50%;
            cursor: pointer;
            opacity: .6;
        }
        #prev {
            left: 10px;
        }
        #next {
            right: 10px;
        }
        #prev:hover,
        #next:hover {
            opacity: 1;
        }
        #prev:hover path,
        #next:hover path {
            fill: #fff;
        }

3.JS部分

        const swiperList = document.querySelector('.swiper-img')
        const swiperActive = document.querySelector('.swiper-active')

        //动态渲染,根据swiper图片的数量,渲染img,li的html结构
        function render(index) {
            for (let i = 0; i < index; i++) {
                //这里通过直接插入<同级>images文件夹下以    swiper-从1开始递增.jpg 命名的,若图片为png,此处则修改为png
                //此方法的缺点文件后缀格式必须是相同的,如果是不同的,可以创建一个类似数组
                /*const imgList = [
                1.jpg,
                2.png,
                ...
                ]*/
                //然后修改模板字符串的插入值,以实现不同格式的图片插入
                //swiperList.innerHTML+=`<img src="images/swiper-${imgList[i]}">`
                swiperList.innerHTML += `<img src="images/swiper-${i + 1}.jpg">`
                swiperActive.innerHTML += i == 0 ? '<li class="active"></li>' : '<li></li>'
            }
        }
        //不要忘了调用创建的渲染函数,传入需要渲染和展示的轮播图片的数量
        render(6)

        const swiperImg = document.querySelectorAll('.swiper-img img')
        const swiperPointe = document.querySelectorAll('.swiper-active li')

        //分别复制首尾元素
        const firstChild = swiperList.firstElementChild.cloneNode(true)
        const lastChild = swiperList.lastElementChild.cloneNode(true)
        //将复制的第一个子元素,添加到末尾
        swiperList.append(firstChild)
        //将复制的最后一个子元素,添加开头
        swiperList.insertBefore(lastChild, swiperList.firstChild)
        
        //初始状态让复制到第一张的图片隐藏,显示轮播图第一张图片
        swiperList.style.transform = `translateX(-${100 / (swiperImg.length + 2)}%)`

        //定义一个索引
        let moveID = 0
        //封装一个函数执行轮播图的切换和圆点样式的切换
        function moveTo(index) {
            swiperList.style.transition = 'all .5s'
            swiperList.style.transform = `translateX(-${(index + 1) * 100 / (swiperImg.length + 2)}%)`
            //先去掉已有圆点样式,后添加
            document.querySelector('.active').classList.remove('active')
            swiperPointe[index].classList.add('active')
        }

        // 自动轮播,创建计时器,每5000ms(5s)执行一次,本案例通过直接调用click,点击右侧箭头实现自动轮播
        let timerID = setInterval(() => {
            next.click()
        }, 5000);

        function autoChange() {
            clearTimeout(timerID)
            timerID = setInterval(() => {
                next.click()
            }, 5000);
        }
        //遍历白点,点击切换
        swiperPointe.forEach((item, i) => {
            item.onclick = () => {
                autoChange()
                moveID = i
                moveTo(moveID)
            }
        });

        //左右箭头
        const prev = document.querySelector('#prev')
        const next = document.querySelector('#next')
        prev.addEventListener('click', () => {
            autoChange()
            moveID--
            if (moveID < 0) {
                swiperList.style.transition = 'none'
                swiperList.style.transform = `translateX(-${(swiperImg.length + 1) * 100 / (swiperImg.length + 2)}%)`
                //随便调用一个可以使浏览器重绘的内置方法
                swiperList.offsetHeight
            }
            //判断,当moveID小于0的时候,给它重新赋值为轮播图数量-1(-1因为索引从0开始)
            moveID = moveID < 0 ? swiperImg.length - 1 : moveID
            //调用封装好的moveTO函数,切换图片
            moveTo(moveID)
        })
        next.addEventListener('click', () => {
            autoChange()
            moveID++
            if (moveID == swiperImg.length) {
                swiperList.style.transition = 'none'
                swiperList.style.transform = `translateX(0)`
                swiperList.offsetHeight
            }
            //判断,当moveID等于轮播图数量时(也就是索引值等于轮播图数量)重新赋值到第一张图的索引0,给它重新赋值为轮播图数量-1(-1因为索引从0开始)
            moveID = moveID == swiperImg.length ? 0 : moveID
            moveTo(moveID)
        })


以上为完整轮播图的实现代码,下面部分为局部设计调整


样式设计(滑动指示条)

在上面结构内容的基础上对指示条的样式进行设计调整

lunbo_2

HTML修改

在最外层盒子class="swiper-box"的盒子中添加一个如下class="swiper-line"的子元素div

        <div class="swiper-line"></div>

CSS修改

        /*修改以下代码*/
        .swiper-active {
            width: 20%;
            height: 8px;
            display: flex;
            flex-direction: row;
            align-items: center;
            margin-bottom: 20px;
            z-index: 1;
        }

        .swiper-active li {
            height: 100%;
            background: #fff;
            transition: all .5s;
            cursor: pointer;
        }
        
        /*添加以下代码*/
        .swiper-active li:not(:nth-child(1)) {
            border-left: 1px dashed #ccc;
        }

        .swiper-line {
            height: 8px;
            position: absolute;
            bottom: 20px;
            left: 40%;
            background: rgb(51, 51, 250);
            z-index: 2;
            transition: all .5s;
        }

JS修改

1.添加第三、四行代码到如图位置

        const swiperImg = document.querySelectorAll('.swiper-img img')
        const swiperPointe = document.querySelectorAll('.swiper-active li')
        

        //添加这两行代码
        const swiperLine = document.querySelector('.swiper-line')
        swiperLine.style.width = `${20 / swiperPointe.length}%`


        //分别复制首尾元素
        const firstChild = swiperList.firstElementChild.cloneNode(true)
        const lastChild = swiperList.lastElementChild.cloneNode(true)
        //将复制的第一个子元素,添加到末尾
        swiperList.append(firstChild)
        //将复制的最后一个子元素,添加开头
        swiperList.insertBefore(lastChild, swiperList.firstChild)
        swiperList.style.transform = `translateX(-${100 / (swiperImg.length + 2)}%)`

2.修改moveTo函数

        function moveTo(index) {
            swiperList.style.transition = 'all .5s'
            swiperList.style.transform = `translateX(-${(index + 1) * 100 / (swiperImg.length + 2)}%)`
            //修改为
            swiperLine.style.left = `${index * 20 / swiperPointe.length + 40}%`
        }


总结

轮播图的种类,代码的风格和实现方法有很多种,同样的轮播图结构功能不同的人写的代码都各式各样的,只要掌握了方法就按照自己的思路代码习惯来实现,本案例仅供参考交流

  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用原生JavaScript实现轮播图完整代码HTML: ```html <div class="slider"> <div class="slider-container"> <div class="slider-item"> <img src="image1.jpg"> </div> <div class="slider-item"> <img src="image2.jpg"> </div> <div class="slider-item"> <img src="image3.jpg"> </div> </div> <div class="slider-prev">prev</div> <div class="slider-next">next</div> <div class="slider-dots"> <span class="dot active"></span> <span class="dot"></span> <span class="dot"></span> </div> </div> ``` CSS: ```css .slider { position: relative; width: 100%; height: 400px; overflow: hidden; } .slider-container { position: absolute; width: 300%; height: 100%; left: -100%; display: flex; transition: left 0.5s ease-in-out; } .slider-item { width: 33.333%; height: 100%; } .slider-item img { width: 100%; height: 100%; object-fit: cover; } .slider-prev, .slider-next { position: absolute; top: 50%; transform: translateY(-50%); width: 50px; height: 50px; border-radius: 50%; background-color: rgba(0, 0, 0, 0.5); color: #fff; font-size: 24px; text-align: center; cursor: pointer; transition: background-color 0.3s ease-in-out; } .slider-prev:hover, .slider-next:hover { background-color: rgba(0, 0, 0, 0.8); } .slider-prev { left: 20px; } .slider-next { right: 20px; } .slider-dots { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); display: flex; } .slider-dots .dot { width: 12px; height: 12px; margin: 0 8px; border-radius: 50%; background-color: rgba(255, 255, 255, 0.5); cursor: pointer; transition: background-color 0.3s ease-in-out; } .slider-dots .dot.active { background-color: #fff; } .slider-dots .dot:hover { background-color: rgba(255, 255, 255, 0.8); } ``` JavaScript: ```javascript const slider = document.querySelector('.slider'); const sliderContainer = document.querySelector('.slider-container'); const sliderItems = document.querySelectorAll('.slider-item'); const prevBtn = document.querySelector('.slider-prev'); const nextBtn = document.querySelector('.slider-next'); const dots = document.querySelectorAll('.dot'); // 当前显示的图片索引 let currentIndex = 0; // 偏移量,用于控制 slider-container 的 left 值 let offset = 0; // 自动轮播定时器 let timer = null; // 自动轮播 function autoPlay() { timer = setInterval(() => { next(); }, 3000); } // 显示指定索引的图片 function show(index) { if (index < 0) { index = sliderItems.length - 1; } else if (index >= sliderItems.length) { index = 0; } currentIndex = index; offset = -currentIndex * slider.offsetWidth; sliderContainer.style.left = offset + 'px'; // 更新 dots 的激活状态 dots.forEach(dot => dot.classList.remove('active')); dots[currentIndex].classList.add('active'); } // 下一张图片 function next() { show(currentIndex + 1); } // 上一张图片 function prev() { show(currentIndex - 1); } // 点击 dots 切换图片 dots.forEach((dot, index) => { dot.addEventListener('click', () => { show(index); }); }); // 点击 prev 和 next 切换图片 prevBtn.addEventListener('click', prev); nextBtn.addEventListener('click', next); // 鼠标悬停停止自动轮播,离开恢复自动轮播 slider.addEventListener('mouseenter', () => { clearInterval(timer); }); slider.addEventListener('mouseleave', () => { autoPlay(); }); // 初始化轮播图,显示第一张图片,开始自动轮播 show(0); autoPlay(); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值