<html>
<head>
    <title>图片轮播</title>
    <style>
        .swiper-container {
            width: 500px;
            height: 300px;
            margin: 0 auto;
            position: relative;
            overflow: hidden;
        }
<pre><code>    .swiper-wrapper {
        width: 100%;
        height: 100%;
        position: relative;
    }

    .swiper-slide {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        transition: opacity .5s ease;
        background-size: cover;
    }

    .swiper-slide-active {
        opacity: 1;
    }

    .button {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        width: 50px;
        height: 50px;
        background: rgba(0, 0, 0, .5);
        color: #fff;
        text-align: center;
        line-height: 50px;
        font-size: 20px;
        cursor: pointer;
    }

    .prev {
        left: 0;
    }

    .next {
        right: 0;
    }
&lt;/style&gt;
</code></pre>
</head>
<body>
<div class='swiper-container'>
    <div class='swiper-wrapper'>
        <div class='swiper-slide zoom-in lunbo'
             style='background-image: url(static/picture/01.png);'
             data-v-a549dd98></div>
        <div class='swiper-slide zoom-in lunbo'
             style='background-image: url(static/picture/02.png);'
             data-v-a549dd98></div>
        <div class='swiper-slide zoom-in lunbo'
             style='background-image: url(static/picture/03.png);'
             data-v-a549dd98></div>
    </div>
    <div class='button prev'>&lt;</div>
    <div class='button next'>&gt;</div>
</div>
<script>
    var swiperWrapper = document.querySelector('.swiper-wrapper');
    var swiperSlide = document.querySelectorAll('.swiper-slide');
    var prevBtn = document.querySelector('.prev');
    var nextBtn = document.querySelector('.next');
    var currentIndex = 0;
    var len = swiperSlide.length;
<pre><code>swiperSlide[currentIndex].classList.add('swiper-slide-active');

function prev() {
    swiperSlide[currentIndex].classList.remove('swiper-slide-active');
    currentIndex--;
    if (currentIndex &lt; 0) {
        currentIndex = len - 1;
    }
    swiperSlide[currentIndex].classList.add('swiper-slide-active');
}

function next() {
    swiperSlide[currentIndex].classList.remove('swiper-slide-active');
    currentIndex++;
    if (currentIndex &gt;= len) {
        currentIndex = 0;
    }
    swiperSlide[currentIndex].classList.add('swiper-slide-active');
}

prevBtn.addEventListener('click', prev);
nextBtn.addEventListener('click', next);

setInterval(next, 3000);
</code></pre>
</script>
</body>
</html>
纯 JavaScript 实现图片轮播效果 - 带有上一张和下一张按钮

原文地址: https://www.cveoy.top/t/topic/lQwB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录