0

我已经为我的站点创建了一个显示统计数据的图形,并且我使用 countTo jQuery 函数使它看起来非常棒“从零开始”“计数”。然而,我遇到的问题是 countTo 脚本在页面加载时启动,所以如果我不向下滚动到在 4 秒内显示统计信息的位置 +/- 动画(再次,当页面加载时发生),那么我看到的只是最终数字,我错过了动画。我想做的是让它在元素进入窗口后加载。

抱歉,如果我在这里遗漏了一个明显的解决方案,我正在自学并且仍在学习曲线上。任何帮助将不胜感激!

这是我正在使用的脚本:

    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.countTo = function(options) {
    // merge the default plugin settings with the custom options
    options = $.extend({}, $.fn.countTo.defaults, options || {});

    // how many times to update the value, and how much to increment the value on each update
    var loops = Math.ceil(options.speed / options.refreshInterval),
        increment = (options.to - options.from) / loops;

    return $(this).each(function() {
        var _this = this,
            loopCount = 0,
            value = options.from,
            interval = setInterval(updateTimer, options.refreshInterval);

        function updateTimer() {
            value += increment;
            loopCount++;
            $(_this).html(value.toFixed(options.decimals));

            if (typeof(options.onUpdate) == 'function') {
                options.onUpdate.call(_this, value);
            }

            if (loopCount >= loops) {
                clearInterval(interval);
                value = options.to;

                if (typeof(options.onComplete) == 'function') {
                    options.onComplete.call(_this, value);
                }
            }
        }
    });
};

$.fn.countTo.defaults = {
    from: 0,  // the number the element should start at
    to: 100,  // the number the element should end at
    speed: 1000,  // how long it should take to count between the target numbers
    refreshInterval: 100,  // how often the element should be updated
    decimals: 0,  // the number of decimal places to show
    onUpdate: null,  // callback method for every time the element is updated,
    onComplete: null,  // callback method for when the element finishes updating
};
})(jQuery);


jQuery(function($) {
    $('.timer').countTo({
        from: 0,
        to: 70218,
        speed: 4000,
        refreshInterval: 20,
        onComplete: function(value) {
            console.debug(this);
        }
    });
});
</script>
4

2 回答 2

0

你可以试试jQuery Waypoints

我正在做类似的事情,也许这会让你朝着正确的方向开始:

$('figure.infographic').each(function(i, el){
    $.waypoints('refresh'); 

    function animateNumber(){
        numEl.countTo({
            speed: 800
        });
    }

    $(this).waypoint(function(direction) {
        if (direction === 'down') {
            animateNumber();
        }
    }, {
        offset: 'bottom-in-view'
    }).waypoint(function(direction) {
        if (direction === 'up') {
            animateNumber();
        }
    }, {
        offset: 0
    });
});
于 2014-05-24T19:31:12.453 回答
-1

当 window.scrollTop() 等于包装器的偏移量时,为什么不调用函数 countTo ..

于 2016-01-11T15:46:28.673 回答