How to detect if an element has scrolled out, but

2019-03-21 22:18发布

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.

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-03-21 22:55

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');
    }
});
查看更多
等我变得足够好
3楼-- · 2019-03-21 23:03

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');
    }
});
查看更多
登录 后发表回答