Swiper - 初始化时宽度错误,调整大小后宽度正确

pau*_*aem 9 html javascript css jquery swiper

我正在使用 Swiper 进行一个项目,并且在调整窗口大小后一切正常。但是在初始化时幻灯片的宽度不正确。我尝试在本地复制它,但没有成功。我为每个视图设置了 4 张幻灯片,但它正在计算 3 1/2 张幻灯片的宽度。我从我的配置中清除了除 slidesPerView 之外的所有内容,但根本没有任何变化。会不会与其他框架或插件发生某种冲突?如果需要其他信息来解决此问题,请询问!:-)

编辑

HTML:

<div id="gallery_container">
    <div id="galleryLeft"></div>
    <div id="gallery-swiper">
        <div class="swiper-wrapper">
            <div class="swiper-slide">
                ...
            </div>
        </div>
    </div>
    <div id="galleryRight"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

初始化:

(function($) {
    $(document).ready(function() {
        var gallery_swiper = new Swiper('#gallery-swiper', {
            slidesPerView: 3,
            spaceBetween: 0,
            speed: 500,
            prevButton: '#galleryLeft',
            nextButton: '#galleryRight'
        });

        var slides = gallery_swiper.slides.length;
        if(slides < 4) {
            $('#galleryLeft').css("display", "none");
            $('#galleryRight').css("display", "none");
            $('#gallery_container').css({
                "padding": "0"
            });
        }
    });
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

也许值得注意的是 gallery_container 是响应式的。滑块位于列内。

Mic*_*ber 6

经过一些浪费时间后,简单而不错的解决方案对我有用:

window.addEventListener('load', () => {
// init swiper here
}, false);
Run Code Online (Sandbox Code Playgroud)

当整个页面(包括所有依赖资源,例如样式表和图像)加载时,将触发 load 事件。

文档:
https ://developer.mozilla.org/en-US/docs/Web/API/Window/load_event


如果这对您不起作用,请确保查看我找到此修复程序的线程:
src: https: //github.com/nolimits4web/swiper/issues/2218#issuecomment-509683102

还有其他可能的解决方案(例如:浏览器扩展也可能导致此问题):

干杯,我希望这对某人有帮助!