javascript 如何在移动触摸屏设备上禁用滚动和重新启用滚动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17769990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to disable scrolling and re-enable scrolling on a mobile touch screen device
提问by alutz
This is not so much of a question as it is an solution to the question.
这与其说是问题,不如说是问题的解决方案。
It was difficult find a solution until I stumbled across the answer in added by hallodom (How to disable scrolling temporarily?) which was responding to a slightly different problem.
很难找到解决方案,直到我偶然发现了由 halodom(如何暂时禁用滚动?)添加的答案,该答案正在响应一个稍微不同的问题。
I wanted to explicitly document an answer to the problem. Other solutions are most welcome and would add to the conversation.
我想明确记录这个问题的答案。其他解决方案是最受欢迎的,并将添加到对话中。
hallodom's solution was:
Hallodom 的解决方案是:
For mobile devices, you'll need to handle the touchmove
event:
对于移动设备,您需要处理touchmove
事件:
$('body').bind('touchmove', function(e){e.preventDefault()})
And unbind to re-enable scrolling. Tested in iOS6 and Android 2.3.3
并取消绑定以重新启用滚动。在 iOS6 和 Android 2.3.3 中测试
$('body').unbind('touchmove')
I used hallodom's solution by simply attaching them to functions called when an object in my DOM was clicked:
我使用了 Hallodom 的解决方案,只需将它们附加到单击 DOM 中的对象时调用的函数:
$('body').on('click', 'button', function(e){
if($(this).prop('checked')){
disable_scroll();
}else{
enable_scroll();
}
});
function disable_scroll() {
$('body').bind('touchmove', function(e){e.preventDefault()});
}
function enable_scroll() {
$('body').unbind('touchmove');
}
回答by Lucas Willems
Try this code :
试试这个代码:
var scroll = true
$(document).bind('touchmove', function(){
scroll = false
}).unbind('touchmove', function(){
scroll = true
})
$(window).scroll(function() {
if ($('button').is(':checked') && scroll == false) {
$(document).scrollTop(0);
}
})