disable scrolling when trigger owl carousel on mob

2019-08-18 06:19发布

问题:

I noticed when using Owl Carousel 2, while slide the item in mobile viewing, the browser also can be move up and down. Try to disabling the scroll function when trigger the Owl Carousel 2 prev and next function in mobile but it still doesn't work.

$('.owl-carousel').owlCarousel({
    loop:true,
    margin:5,
    nav:true,
    items:2,
});
// $('.owl-carousel').bind("mousewheel", function() {return false;});
$('.owl-carousel').bind('touchmove', function(e){e.stopPropagation(); alert('allow scroll');});

Appreciated the answer from expert out here.

Thank you.

回答1:

I made this work with the help of OwlCarousel2 events.

There are 2 events we can use together for this purpose:

  1. drag.owl.carousel fires when user start to drag
  2. dragged.owl.carousel fires when dragging finished

And this make it work like how we want it:

var owl = $('.owl-carousel');
owl.owlCarousel({
    //  your options
});

owl.on('drag.owl.carousel', function(event) {
    $('body').css('overflow', 'hidden');
});

owl.on('dragged.owl.carousel', function(event) {
    $('body').css('overflow', 'auto');
});

So; it use css overflow to disable scrolling when dragging started and enables it back when it finished.



回答2:

This works on iOS & VueJS.

var owl = $('.owl-carousel');
    owl.owlCarousel({
    //  your options
})

// disable scroll
owl.on('drag.owl.carousel', function(event) {
    document.ontouchmove = function (e) {
        e.preventDefault()
    }
})

// enable scroll
owl.on('dragged.owl.carousel', function(event) {
    document.ontouchmove = function (e) {
        return true
    }
})