need help 2024-09-04 18:05 采纳率: 25%
浏览 11

swiper轮换图片图片,图片偏移

在使用swiper轮换图片时,点击下一个,swiper会向右侧偏移,如何解决,js 代码如下

 <script>
        const swiper = new Swiper('.swiper-container', {
            slidesPerView: 3, // 每次显示3张图片
            spaceBetween: 10, // 图片间距
            loop: true, // 无缝轮换
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
            },
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            observer: true, 
            observeParents: true, 
        });
    </script>

```

  • 写回答

2条回答 默认 最新

  • 吃不了席 2024-09-04 18:06
    关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    要解决这个问题,你需要修改swiper对象中的navigation属性以改变导航按钮的位置。以下是修复后的JavaScript代码:

    <script>
            const swiper = new Swiper('.swiper-container', {
                slidesPerView: 3, // 每次显示3张图片
                spaceBetween: 10, // 图片间距
                loop: true, // 无缝轮换
                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                },
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },
                observer: true, 
                observeParents: true, 
            });
        </script>
    

    然后,在HTML中添加新的<button>元素并将其与nextEl属性绑定到正确的元素上:

    <button class="swiper-button-prev">Previous</button>
    <button class="swiper-button-next">Next</button>
    

    现在,当用户点击导航按钮时,轮播将会相应地移动。

    如果你想要进一步控制导航按钮的移动距离(例如,左移或右移),可以在navigation属性中设置一个函数,如下所示:

    <script>
        function handleNavigation(swiper) {
            if (swiper.el.classList.contains('prev')) {
                swiper.slidePrev();
            } else if (swiper.el.classList.contains('next')) {
                swiper.slideNext();
            }
        }
    
        const swiper = new Swiper('.swiper-container', {
            ...其他配置...
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
                on: handleNavigation,
            },
            observer: true, 
            observeParents: true, 
        });
    </script>
    

    这段代码会在每次导航操作后调用handleNavigation函数,并将滑动的el元素附加到相应的导航按钮上。这样,无论何时用户点击导航按钮,轮播都会相应地移动。

    评论

报告相同问题?

问题事件

  • 创建了问题 9月4日