2017-06-14 48 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); 
相关问题