Disabling Owl Carousel at a specific viewport width

前端 未结 5 1339
说谎
说谎 2021-02-19 17:38

I\'m currently using Owl Carousel to show a gallery on desktop/laptop sized devices. However on smaller devices I\'d like to disable the plugin and show each image stacked under

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-19 18:26

    I had to disable plugin if the screen width is bigger than 854px. Sure, you can change the code to fit your needs. Here is my solution:

    1. Check the viewport width before call the plugin.
    2. If width is good to call the plugin, call the plugin. Else add the 'off' class to show as if the plugin has already been called and destroyed.
    3. When resizing:
      3.1. If width is good to call the plugin AND the plugin hasn't been called yet or it was destroyed earlier (I use the 'off' class to know it), THEN call the plugin.
      3.2. if width isn't good to call the plugin AND the plugin is active now, THEN destroy it with Owl's trigger event destroy.owl.carousel and remove the unnecessary wrapper element 'owl-stage-outer' after it.
    $(function() {
        var owl = $('.owl-carousel'),
            owlOptions = {
                loop: false,
                margin: 10,
                responsive: {
                    0: {
                        items: 2
                    }
                }
            };
    
        if ( $(window).width() < 854 ) {
            var owlActive = owl.owlCarousel(owlOptions);
        } else {
            owl.addClass('off');
        }
    
        $(window).resize(function() {
            if ( $(window).width() < 854 ) {
                if ( $('.owl-carousel').hasClass('off') ) {
                    var owlActive = owl.owlCarousel(owlOptions);
                    owl.removeClass('off');
                }
            } else {
                if ( !$('.owl-carousel').hasClass('off') ) {
                    owl.addClass('off').trigger('destroy.owl.carousel');
                    owl.find('.owl-stage-outer').children(':eq(0)').unwrap();
                }
            }
        });
    });
    

    And a bit of CSS to show disabled Owl element:

    .owl-carousel.off {
        display: block;
    }
    

提交回复
热议问题