简体   繁体   中英

Prevent HTML Scrolling When scrolling inside element, without hiding scrollbar

I want to prevent scrolling of the body or html when user is scrolling inside the menu. However, I DON'T WANT to set $('html').css('overflow','hidden'); because this makes the entire document shift right. I just want to disable the HTML scroll when scrolling or swiping inside the menu. I tried to search this topic a lot, but nothing I found really worked for me.

FIDDLE

Set this when the menu is open:

var thisHeight = $(window).scrollTop();
$(window).on('scroll', function() {
    $('html,body').scrollTop(thisHeight);
});

$('.noScroll').on('touchstart' , function(e) { e.preventDefault(); })
$('.noScroll').on('touchmove' , function(e) { e.preventDefault(); })

And this when it closes:

$(window).off('scroll');
$('.noScroll').off('touchstart');
$('.noScroll').off('touchmove');
$('.noScroll').on('touchstart' , function(){ return true; });        
$('.noScroll').on('touchmove' , function(){ return true; });

You need to add a class="noScroll" in the text div for it, check FIDDLE.

iOS solution based on:

How to unbind a listener that is calling event.preventDefault() (using jQuery)?


JSFIDDLE: http://jsfiddle.net/m2ga2ygo/4/ .

Uploaded test: https://liebdich.biz/develop/iosMobile.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM