Jquery detect scroll once

回眸只為那壹抹淺笑 提交于 2019-12-05 07:26:36

问题


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

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

If have this inline code:

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 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.

Any help would be greatly appreciated.

David


回答1:


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.

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.

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.

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.

Example:

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


来源:https://stackoverflow.com/questions/20362688/jquery-detect-scroll-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!