滚动高度脚本仅运行一次

时间:2017-01-19 13:52:51

标签: javascript jquery scroll

这绝不是DRY代码,但我试图运行一个脚本,一旦特定元素出现在视口中,就会计算数字。对于.counter-number-products,数字会计入该特定元素,但我似乎无法让它再次为.counter-number-2_products运行。这是代码:

/////////////////////////////////////////
// Counting Up Numbers on Products Page//
/////////////////////////////////////////

function countUp(element) {
    $(element).each( function() {
        console.log('this' , this)
        var $this = $( this ),
            countTo = $this.attr( 'data-count' );
        $( {
            countNum: $this.text()
        } ).animate( {
            countNum: countTo
        }, {
            duration: 2000,
            easing: 'linear',
            step: function() {
                $this.text( Math.floor( this.countNum ) );
            },
            complete: function() {
                $this.text( this.countNum );
                //alert('finished');
            }
        } );
    } );
}//end of countUp()

////////////////////////////////////////////////////////////
// Checking when element is visible for counting animation//
////////////////////////////////////////////////////////////

function checkVisible( elm, eval ) {
console.log(elm)
eval = eval || "object visible";
var viewportHeight = $(window).height(), // Viewport Height
    scrolltop = $(window).scrollTop(), // Scroll Top
    y = $(elm).offset().top,
    elementHeight = $(elm).height();   

if (eval == "object visible") return ((y < (viewportHeight + scrolltop)) && (y > (scrolltop - elementHeight)));
if (eval == "above") return ((y < (viewportHeight + scrolltop)));
}


///////////////////////////////////////////////////////////////////////
// Running countUp() when first numbers on page are visible on scroll//
///////////////////////////////////////////////////////////////////////

$(window).on('scroll',function() {
if (checkVisible($('.counter-number_products'))) {
    var element = $('.counter-number_products');
    countUp(element);
    $(window).off('scroll');
    // console.log('first scroll is running')
} else {
    // console.log('first scroll is not running')
}
});
$(window).on('scroll',function() {
if (checkVisible($('.counter-number-2_products'))) {
    var element = $('.counter-number-2_products');
    countUp(element);
    $(window).off('scroll');
    // console.log('second scroll is running')
} else {
    // console.log('second scroll not running')
}
});

为什么countUp()不会运行两次?

0 个答案:

没有答案