How to detect if an element has scrolled out, but only once?

China☆狼群 提交于 2020-01-01 03:37:34

问题


I am trying to detect if an element has been scrolled out and have done the following code

$(window).bind('scroll', function(){
    var $btn = $('#intro div.summary a[href=#top]');
    if($(window).scrollTop() > ($btn.offset().top+$btn.height())){
        console.log('out');
    }
});

I have an anchor in some body text, that I am hoping to clone and make a fixed nav out of once the div.intro is scrolled out.

My problem is that the code fires as soon as the element is out of view, but keeps firing. So I cannot do any more as anything more will keep firing.

Is there a way to fire 'out' once it's out and 'in' once it's in? Aside from just setting a variable.


回答1:


To execute the event only once you can do

$(window).one('scroll', function(){
    var $btn = $('#intro div.summary a[href=#top]');
    if($(window).scrollTop() > ($btn.offset().top+$btn.height())) {
        console.log('out');
    }
});



回答2:


Well, the easiest solution would be to unbind the event after it fires:

$(window).bind('scroll', function(){
    var $btn = $('#intro div.summary a[href=#top]');
    if($(window).scrollTop() > ($btn.offset().top+$btn.height())) {
        console.log('out');
        $(window).unbind('scroll');
    }
});


来源:https://stackoverflow.com/questions/5033191/how-to-detect-if-an-element-has-scrolled-out-but-only-once

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