1

I have some code, that checks for the visibility of an element on the screen. As soon as it comes in sight by scrolling the page a custom event is triggered. This custom event starts an animation. To prevent this animation to be started over and over the function that starts it is only started once. For that I used the jQuery function .one().

The function to check if element is visible:

checkScrollPos = function() {
    if (objTopPos - scrollPos <= windowHeight / 2) {
        $(document).trigger('objVisible');
    }
}

The function to listen for the event:

evtListener = function() {
    //startAnimation() should only be started once
    $(document).one(
        {
            'objVisible': function(event) {
                startAnimation();
            }
        }
    );
}

Here it all happens:

$(document).ready(function() {
    evtListener();
    $(window).scroll(function () {
        scrollPos = $(document).scrollTop();
        checkScrollPos();
    }
}

Now this all works fine but I extended the checkScrollPos() function to also check if the element gets out of sight again, to then stop the animation. That works fine to. Problem is, as the events trigger, the event-bound functions only are executed one time. So when you scroll teh element in sight, then out of sight and then in sight again the animation will not be executed again (what is the correct behaviour of course). Now I would like to have it that the events are triggered exactly one time but EVERYTIME the element gets in or out of sight and not just one time at all. So basicly I need some kind of reset for the

$(document).one()

function – so that everytime the element gets out of sight, I can use the .one() function again. Is there any way to do that?

4

1 回答 1

0

objVisible每次元素消失时,您都必须绑定事件。

只需evtListener()在元素消失后调用,以便objVisible再次绑定事件。

您的代码将是这样的:

checkScrollPos = function() {
    if (objTopPos - scrollPos <= windowHeight / 2) {
        $(document).trigger('objVisible');
    }

    if (/* your condition to check if element is out of sight */) {
        evtListener();
    }
}
于 2013-01-31T15:56:26.070 回答