简体   繁体   English

使用css禁用移动滚动

[英]disable mobile scrolling with css

I want to disable the body from scrolling when a div is in the foreground. 当div在前台时,我想禁止滚动体。 The div is scrollable and I don't want the body to scroll along with it. div是可滚动的,我不希望身体随之滚动。 I accomplished this in a browser but it doesn't work in mobile. 我在浏览器中完成了这个,但它在移动设备中不起作用。 What do I need to change from when the div is open: 从div打开时我需要更改什么:

$('body').css('overflow', 'hidden');

to when the div is closed: 当div关闭时:

$('body').css('overflow', 'auto');

But as I said, it doesn't work in mobile (iOS or Android). 但正如我所说,它不适用于移动设备(iOS或Android)。 I tried epreventdefault() also and that didn't help. 我也尝试了epreventdefault(),但没有帮助。 The css gets changed with onclick events... 通过onclick事件改变了css ......

this worked for me: 这对我有用:

document.body.scroll = "no";
document.body.style.overflow = 'hidden';
document.height = window.innerHeight;

document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });

After facing a similar problem with mobile scrolling causing a mess with my scrollable divs and unwanted scrolling body, the touchmove listener event is the key. 在面对移动滚动的类似问题导致我的可滚动div和不需要的滚动体的混乱之后,touchmove侦听器事件是关键。 A couple caveats I came across tho that I had to figure out. 我遇到了一些警告,我必须弄明白。 One, in order to remove the event listener, and give your body back its scrolling (as was my case with a menu that slide in from right and covered the entire window) you have to name the function that gets included iun the event listener, that way you can call the same function to be removed with removeEventListener. 一,为了删除事件监听器,并让你的身体返回其滚动(就像我的情况一样从右边滑入并覆盖整个窗口的菜单)你必须命名包含在事件监听器中的函数,这样你可以使用removeEventListener调用相同的函数。

var prevent = function(e){ 
    e.preventDefault();
};

function menuOpen(){
    document.body.addEventListener('touchmove', prevent);
};

function menuClose(){
    document.body.removeEventListener('touchmove', prevent);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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