问题
I want to disable vertical scrolling on webpage while swiping the carousel horizontally on mobile devices. I'm using the Owl carousel.
I have tried to use css overflow: hidden to html, body but doesn't work. Tried the other solutions out there but they don't work. The code I have tried is down below.
// Tried this but doesn't work
var owl = $j(".owl-carousel");
owl.on('drag.owl.carousel', function(event) {
document.ontouchmove = function (e) {
e.preventDefault()
}
});
owl.on('dragged.owl.carousel', function(event) {
document.ontouchmove = function (e) {
return true
}
});
// Tried this but doesn't work
owl.on('drag.owl.carousel', function(event) {
$('body').css('overflow', 'hidden');
});
owl.on('dragged.owl.carousel', function(event) {
$('body').css('overflow', 'auto');
});
回答1:
Did you try this where you initialize the carousel?
$j(".owl-carousel").owlCarousel({
onDragged: function() {
$j('body').css('overflow', 'auto');
},
onDrag: function() {
$j('body').css('overflow', 'hidden');
}
});
Also, I'd recommend just adding/removing a class to the body/html tag which adds the overflow, rather than using JS to manipulate the CSS itself.
UPDATE: Based on the comments, it appears there is a known bug. Someone else asked this same question and got an answer here: disable scrolling when trigger owl carousel on mobile device
For data removal purposes, I'll copy the answer that someone claimed works on IOS. Please test and tell us if it worked for your application:
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
}
})
I would still recommend leaving your current code as is, including the onDrag and onDragged functions, and just update it. Replace your code inside your script tag with this:
var $j = jQuery.noConflict();
$j( document ).ready( function() {
var owl = $j( ".owl-carousel" ).owlCarousel( {
stagePadding: 90,
loop: true,
lazyLoad: true,
dots: false,
margin: 10,
nav: false,
onDragged: function() {
$j( 'body' ).css( 'overflow', 'auto' );
},
onDrag: function() {
$j( 'body' ).css( 'overflow', 'hidden' );
},
responsive: {
0: {
items: 2
},
500: {
items: 4
},
1000: {
items: 5
}
}
} );
// 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;
}
} );
} );
来源:https://stackoverflow.com/questions/57426052/disable-vertical-scrolling-while-swiping-on-touch-device-using-owl-carousel