Javascript 检测用户是否开始滚动jQuery
这是我的密码:Javascript 检测用户是否开始滚动jQuery,javascript,jquery,Javascript,Jquery,这是我的密码: if ($('document').scrollTop() < 0) { //Automatic Scroll setTimeout(function () { $('html, body').animate({ scrollTop: $('.main-header').offset().top - 0 }, 1800, 'easeInOutQuad'); },8000); } if($('document').scrollTop(
if ($('document').scrollTop() < 0) {
//Automatic Scroll
setTimeout(function () {
$('html, body').animate({
scrollTop: $('.main-header').offset().top - 0
}, 1800, 'easeInOutQuad');
},8000);
}
if($('document').scrollTop()<0){
//自动滚动
setTimeout(函数(){
$('html,body')。设置动画({
scrollTop:$('.main header').offset().top-0
},1800,“易思诺特广场”);
},8000);
}
如果用户不滚动,页面将自动滚动到某个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();
if($('document').scrollTop()<0){
//自动滚动
设置超时(triggerScroll,8000);
}
函数triggerScroll(){
$('html,body')。设置动画({
scrollTop:$('.main header').offset().top-0
},1800,“易思诺特广场”);
}
//手动触发:
triggerScroll();
试试这个
document.body.scrollTop === 0
要检测用户是否没有滚动,我要做的是设置一个
hasScrolled
变量
var hasScrolled=false代码>
如果用户滚动,则将该变量更改为“true”:
document.addEventListener(“滚动”,函数(){hasScrolled=true;})代码>
然后执行设置超时,查看用户是否在8秒内滚动,如果没有,则执行以下操作:
setTimeout(triggerScroll,8000)代码>
在triggerScroll函数中,第一行可以是if(hasScrolled)return
,这样,如果他们已经滚动,它就不会运行
您需要使用设置超时
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" );
});
演示
函数setUncollEvent(滚动超时,回调)
{
$(窗口)。滚动(函数(){
如果(window.scrollTimer)
{
clearTimeout(window.scrollTimer);//如果滚动已经开始,则清除超时
}
window.scrollTimer=setTimeout(函数(){
callback();//如果scroll已空闲超过srollms,则调用回调
},滚动超时);
});
}
SetUncollEvent(100,函数(){
console.log(“100ms内无滚动”);
});代码>
.container
{
宽度:1000px;
高度:1000px;
背景色:#ccc;
}
jqueryI中的use on scroll事件侦听器在我的答案中添加了一个JSFIDLE,