如何在移动设备上创建模态导航菜单并防止身体滚动?

时间:2013-02-01 09:10:22

标签: javascript android mobile scroll modal-dialog

我寻找并测试了许多解决方案,但我无法使其工作。我希望子导航菜单(模态)能够在显示时滚动,而不是身体。

我试过了:

1:当模态打开时,Javascript将CSS属性更改为“fixed”:

var main = document.getElementById('main');
main.setAttribute("style", "position: fixed;");

问题:如果您在打开模式时滚动页面,页面会上升(“固定”也意味着您无法使用滚动条)

2:当模态打开时,Javascript将CSS属性更改为“溢出隐藏”:

document.body.setAttribute("style", "overflow: hidden;");

问题:无法在移动设备上运行,仍然滚动(我使用的是Android)。

3:Javascript禁用触摸事件:

var main = document.getElementById('main');
main.addEventListener('touchstart', function(e){ e.preventDefault(); });
main.addEventListener('scroll', function(e){ e.preventDefault();});
main.addEventListener('touchmove', function(e){ e.preventDefault();});

问题:除非您从子导航菜单中开始触摸,否则可以正常工作。

请参阅此内容以更好地理解我的意思:http://i45.tinypic.com/ajl3rt.png

然后,当显示叠加菜单时,如何防止身体在移动设备中滚动?

1 个答案:

答案 0 :(得分:0)

我有类似的问题。通常,overflow:hidden在桌面上完成此操作。对于移动设备,您还需要应用固定位置。因此,当您的对话框处于活动状态时,将“.noscroll”类添加到正文:

body.noscroll{
overflow:hidden;
position:fixed;
}
相关问题