开发者

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

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.summar开发者_C百科y 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.


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');
    }
});


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');
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜