如何计算滚动触发的jQuery?

时间:2016-01-14 15:44:05

标签: jquery scroll count

您好我正在尝试构建一个计数器,当对象滚动到该计数器时会计数。它适用于滚动,但再次滚动时刷新。默认间隔设置为1.

我如何只计算一次然后停止?

$(window).scroll( function(){
    /* Count Up Numbers on Scroll */
    $('.count-up').each( function(i){

        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        /* If the object is completely visible in the window, fade it it */
        if( bottom_of_window > bottom_of_object ){

            $(this).countTo(); 
        }
    });
});

1 个答案:

答案 0 :(得分:0)

你需要有某种“旗帜”或触发器,你在第一次滚动后触发它,一旦它被触发你就不会再计算了,例如:

var countIt = true;

$(window).scroll( function(){
    /* Count Up Numbers on Scroll */
    $('.count-up').each( function(i){

        var bottom_of_object = $(this).offset().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        /* If the object is completely visible in the window, and countIt is true
           thenfade it in        
        */
        if( bottom_of_window > bottom_of_object && countIt ){

            $(this).countTo(); 
          
            /* set countIt flag to false so that it won't play it again
               as this will be false, the above condition won't met anymore
            */
            countIt = false;
        }
    });
});