最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I reinitialize a swiper.js instance after destroying it? - Stack Overflow

programmeradmin2浏览0评论

I want to be able to toggle between a slider view and a grid view with a button. I start off with the slider view, initialized like so:

var vis = document.getElementById('vis'),
    swiperOpts = {
            direction: dir,
            loop: true,
            slidesPerView: 1,
            mousewheel: true,
            keyboard: {
                enabled: true,
                onlyInViewport: false
            },
            pagination: {
                el: '#swiper-page',
                type: 'fraction',
            },
            autoplay: {delay: 4444},
            on:{
                resize: function(){
                    if(isLand()) swiper.changeDirection('horizontal');
                    else swiper.changeDirection('vertical');

                    swiper.update();
                },
                autoplayStart: function(){
                    playBtn.innerHTML = '<span class="icon-pause2"></span><span class="sr-only">pause</span>';
                },
                autoplayStop: function(){
                    playBtn.innerHTML = '<span class="icon-play3"></span><span class="sr-only">play</span>';
                }
            }
        },
        swiper = new Swiper(vis, swiperOpts)

I switch to the grid view via:

swiper.destroy(false,true);
vis.classList.remove('swiper-container');
vis.classList.add('grid');

This all works fine. But then I reinitialize, sic:

vis.classList.add('swiper-container');
vis.classList.remove('grid');
swiper.init(swiperOpts);
swiper.autoplay.start();

The slider es back and autoplay works for one slide but then it quits working. My buttons don't work, keyboard navigation, pagination, mousewheel; none of that works. But clicking and dragging still works as well as touch navigation. I tried init() with and without the swiperOpts object and I've played with options for destroy() but it hasn't made a difference. I've also tried throwing in swiper.attachEvents() and swiper.update() for good measure but still without result. I can, of course, reload the page but I'd prefer to be able to switch back as seamlessly as possible. What am I missing?

Thanks

发布评论

评论列表(0)

  1. 暂无评论