2013-07-21 63 views
2

这不是一个问题,因为它是问题的解决方案。如何禁用滚动并在移动触摸屏设备上重新启用滚动

很难找到一个解决方案,直到我偶然发现了hallodom(How to disable scrolling temporarily?)所添加的答案,该答案对一个稍微不同的问题做出了响应。

我想明确地记录一个问题的答案。其他解决方案是最受欢迎的,并会增加对话。

hallodom的解决方案是:

对于移动设备,你需要处理touchmove事件:

$('body').bind('touchmove', function(e){e.preventDefault()}) 

和取消绑定重新启用滚动。经测试,在iOS6的和Android 2.3.3

$('body').unbind('touchmove') 

我通过简单地将它们连接到被调用函数使用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'); 
    } 
+0

我编辑了我的答案。 –

+0

我的回答可以帮到你吗? –

回答

1

试试这个代码:

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); 
    } 
}) 
+0

你能否澄清一下在我给出的例子中这将如何工作? – alutz33

+0

哪个例子?用我的代码替换你的代码。 –

+0

对不起,没有看到你的改变。你的例子很好地工作(虽然它会导致一些跳动。)你怎么可以将它绑定到一个复选框,以打开和关闭它,就像我显示的示例中那样? – alutz33

相关问题