这是我的代码:
if ($('document').scrollTop() < 0) {
//Automatic Scroll
setTimeout(function () {
$('html, body').animate({
scrollTop: $('.main-header').offset().top - 0
}, 1800, 'easeInOutQuad');
},8000);
}
如果用户不滚动,页面会自动滚动到某个div。
但是我不知道当用户不滚动时如何触发。
感谢您的帮助!
为了检测用户是否没有滚动,我要做的是设置一个hasScrolled
变量。
var hasScrolled = false;
然后,如果用户滚动,则将该变量更改为"true":
document.addEventListener("scroll", function(){ hasScrolled = true; });
然后执行设置超时,查看用户是否在 8 秒内滚动,如果没有,请执行您的操作:
setTimeout(triggerScroll,8000);
在你的 triggerScroll 函数中,第一行可能会if (hasScrolled) return
,这样它就不会在滚动
https://jsfiddle.net/eergdw3v/
试试这个
document.body.scrollTop === 0
使用 setTimeout
在 scroll
事件中创建计时器
function setUnscrollEvent( scrollTimeout, callback )
{
$( window).scroll(function() {
if ( window.scrollTimer )
{
clearTimeout( window.scrollTimer ); //if the scroll has already started then clear the timeout
}
window.scrollTimer = setTimeout( function(){
callback(); //invoke the callback in case scroll has been idle for srollTimeout ms
}, scrollTimeout );
});
}
您需要以这种方式调用它
setUnscrollEvent( 100, function(){
console.log( "no scrolling for 100ms" );
});
演示
function setUnscrollEvent( scrollTimeout, callback )
{
$( window).scroll(function() {
if ( window.scrollTimer )
{
clearTimeout( window.scrollTimer ); //if the scroll has already started then clear the timeout
}
window.scrollTimer = setTimeout( function(){
callback(); //invoke the callback in case scroll has been idle for srollTimeout ms
}, scrollTimeout );
});
}
setUnscrollEvent( 100, function(){
console.log( "no scrolling for 100ms" );
});
.container
{
width: 1000px;
height: 1000px;
background-color: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>
let scrollHandler = function(e) {
//do your stuff
}
$(window).on("scroll",scrollHandler);
这将为您检测滚动,以回答标题中的问题。不过,我不遵循您在代码下想说的话
导出您的函数,以便您可以在需要时调用它:
if ($('document').scrollTop() < 0) {
//Automatic Scroll
setTimeout(triggerScroll,8000);
}
function triggerScroll() {
$('html, body').animate({
scrollTop: $('.main-header').offset().top - 0
}, 1800, 'easeInOutQuad');
}
// Manual trigger :
triggerScroll();