2017-06-14 49 views
0

使用setTimeout在5秒延遲後使用此javascript滾動到div(#Content)。如何在用戶滾動頁面時取消javascript函數

setTimeout(function() { 
    $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000); 
}, 5000); 

如果用戶在5秒過去之前手動滾動,我將如何去取消此操作。如果用戶滾動,原因是如果頁面然後自動滾動,他們會感到惱火。

嘗試把它放在window.load中,並檢查是否($(window).scrollTop()== 0),但當然這在window.load中總是如此,並且不會被用戶手動取消取消。

謝謝!

回答

1

可以使用例如全局變量,並檢查其設立的事件滾動

var scrolled = false; 
$(document).scroll(function(){scrolled = true;}); 
setTimeout(function() { 
if (!scrolled){ 
    $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 
    1000); } 
    } 
}, 5000); 
+0

非常感謝米哈爾,完美地工作 – simonrl

0

您應定義超時到一個變量能夠與clearTimeout

取消它

查看完整的文檔在這裏:https://www.w3schools.com/jsref/met_win_cleartimeout.asp

只需添加一個事件來檢查oyur滾動和cleart你超時,如果滾動

對於例如:

var myVar = setTimeout(function(){ 
    $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000); 
}, 5000); 

,並取消滾動:

$(document).scroll(function(){ 
clearTimeout(myVar) 
} 
0

您可以通過添加對scroll事件hanlder檢查滾動,然後移除事件處理程序一旦完成檢查的運行邏輯它只需要運行一次。此外,您可以通過在eventHandler代碼中使用clearTimeout來清除setTimeout。

window.addEventListener('scroll', scrollEventHandler); 

function scrollEventHandler(e){ 
    clearTimeout(...setTimeoutid) // Pass in setTimeout Id.  
} 

setTimeout(function() { 
     $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000); 
     window.removeEventListener('scroll', scrollEventHandler); 
}, 5000); 
0

您可以清除超時爲其他人已經表明,也可以讓它運行,但在開始滾動動畫之前執行scrollTop的檢查中:

setTimeout(function() { 
    if ($(window).scrollTop() == 0) { 
     $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000); 
    } 
}, 5000); 
相關問題