jQuery检测滚动一次 [英] Jquery detect scroll once

查看:120
本文介绍了jQuery检测滚动一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已阅读到可以用此行检测到滚动:

Have read that it is possible to detect a scroll with this line:

$('window').one('scroll', function() {  } );

如果有此内联代码:

var TimeVariable=setInterval(function(){ DoJQueryStuff() },300);

function DoJQueryStuff()
 {
 if(typeof jQuery == "undefined") return;
 window.clearInterval(TimeVariable);
 $('body').one('mousemove', function() { alert('mouse'); } );
 $('window').one('scroll', function() { alert('scroll'); } );
 }

DoJQueryStuff每300毫秒调用一次,直到加载JQuery. 如果将鼠标移动到屏幕上的任何位置,都会收到鼠标"警报. 如果我向下滚动,则不会收到滚动"警报. 也就是说,它没有开火.

DoJQueryStuff is called every 300 ms until JQuery is loaded. If I move the mouse anywhere on the screen, I got the "mouse" alert. If I scroll down I do NOT get the "scroll" alert. i.e. it's not firing.

任何帮助将不胜感激.

大卫

推荐答案

首先请使用jquery ready http: //api.jquery.com/ready/方法.我不想说您的实现是错误的,但是比jquery ready方法要慢.

first please use jquery ready http://api.jquery.com/ready/ method. i dont want to say your implementation is wrong but is slower than the jquery ready method.

您的滚动功能基本上不会执行,因为您将其绑定到错误的对象. 当您使用jquery引用window对象时,请勿将其包装在撇号中.

your scroll function don't get executed basically because you are binding it to the wrong object. when you refer to the window object with jquery don't wrap it in apostrophs.

如果这样做,jquery将实习生调用document.getElementsByTagName,并且找不到标记名window,因为window不是window.document节点的子代.因此您的滚动检测功能永远不会被触发,因为jquery无法将eventListener绑定到您提交的元素标记名.

if you do so, jquery will intern call the document.getElementsByTagName and can't find the tagname window because window is not an child of the window.document node. so your scroll detect function never gets fired because jquery can't bind a eventListener to your submited element tagname.

仅将其绑定到window而没有撇号.这会强制jquery将滚动事件直接绑定到window DOM对象,在该对象上滚动时会正确触发您的函数.

simply bind it to window without apostrophs. this forces jquery to bind the scroll event directly to the window DOM object where your function is correctly fired on scroll.

示例:

$(window).ready(function(){
    $(this).one('mousemove', function() { 
        // mouse move
    }).one('scroll', function(){
        // scroll 
    });
});

这篇关于jQuery检测滚动一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆