2013-07-21 135 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

相關問題