48

指定された速度でターゲット数までカウントアップする既存のjQueryプラグインについて誰かが知っているかどうかを調べようとしています。

たとえば、Gmailのホームページの「たくさんのスペース」という見出しの下にあるGoogleの無料ストレージのMB数を見てください。タグには開始番号があり、<span>1秒ごとにゆっくりとカウントアップします。

似たようなものを探していますが、次のように指定できるようにしたいと思います。

  • 開始番号
  • 終了番号
  • 最初から最後まで取得するのにかかる時間。
  • カウンターが終了したときに実行できるカスタムコールバック関数。
4

11 に答える 11

141

私は自分のプラグインを作成することになりました。これが誰かを助ける場合に備えて、これは次のとおりです。

(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);

これを使用する方法のサンプルコードを次に示します。

<script type="text/javascript"><!--
    jQuery(function($) {
        $('.timer').countTo({
            from: 50,
            to: 2500,
            speed: 1000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });
//--></script>

<span class="timer"></span>

JSFiddle でデモを見る: http://jsfiddle.net/YWn9t/

于 2010-03-29T19:28:41.397 に答える
74

jQuery animate関数を使用できます

$({ countNum: 0 }).animate({ countNum: 10 }, {
  duration: 10000, // tune the speed here
  easing: 'linear',
  step: function() {
    // What todo on every count
    console.log(this.countNum);
  },
  complete: function() {
    console.log('finished');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

于 2013-02-04T07:32:37.427 に答える
14

まさにそれを行うための最も小さなコードを作成しました。カウントだけでなく、特定の時間内に実行する必要があるタスクにも使用できます。(たとえば、何かを 5 秒間実行します):

デモ:

var step = function(t, elapsed){
    // easing 
    t = t*t*t;

    // calculate new value
    var value = 300 * t; // will count from 0 to 300

    // limit value ("t" might be higher than "1")
    if( t > 0.999 )
        value = 300;

    // print value (converts it to an integer)
    someElement.innerHTML = value|0;
};

var done = function(){
    console.log('done counting!');
};


// Do-in settings object
var settings = {
    step     : step,
    duration : 3,
    done     : done,
    fps      : 24 // optional. Default is requestAnimationFrame
};

// initialize "Do-in" instance 
var doin = new Doin(settings);
于 2014-07-28T16:56:50.937 に答える
8

プラグインについてはわかりませんが、これはそれほど難しいことではありません。

;(function($) {        
     $.fn.counter = function(options) {
        // Set default values
        var defaults = {
            start: 0,
            end: 10,
            time: 10,
            step: 1000,
            callback: function() { }
        }
        var options = $.extend(defaults, options);            
        // The actual function that does the counting
        var counterFunc = function(el, increment, end, step) {
            var value = parseInt(el.html(), 10) + increment;
            if(value >= end) {
                el.html(Math.round(end));
                options.callback();
            } else {
                el.html(Math.round(value));
                setTimeout(counterFunc, step, el, increment, end, step);
            }
        }            
        // Set initial value
        $(this).html(Math.round(options.start));
        // Calculate the increment on each step
        var increment = (options.end - options.start) / ((1000 / options.step) * options.time);            
        // Call the counter function in a closure to avoid conflicts
        (function(e, i, o, s) {
            setTimeout(counterFunc, s, e, i, o, s);
        })($(this), increment, options.end, options.step);
    }
})(jQuery);

使用法:

$('#foo').counter({
    start: 1000,
    end: 4500,
    time: 8,
    step: 500,
    callback: function() {
        alert("I'm done!");
    }
});

例:

http://www.ulmanen.fi/stuff/counter.php

使い方は一目瞭然だと思います。この例では、カウンターは1000から始まり、500ミリ秒間隔で8秒で4500までカウントし、カウントが完了するとコールバック関数を呼び出します。

于 2010-03-29T18:36:39.247 に答える
2

既存のプラグインについては知りませんが、JavaScript Timing Eventsを使用して自分でプラグインを作成するのはかなり簡単に思えます。

于 2010-03-29T18:28:03.277 に答える
2

別のアプローチ。カウンターには Tween.js を使用します。これにより、カウンターが目的の場所に到達するにつれて、カウンターが減速、加速、バウンス、およびその他の多くの機能を実行できるようになります。

http://jsbin.com/ekohep/2/edit#javascript,html,live

楽しみ :)

PS、jQueryを使用していませんが、明らかに可能です。

于 2012-07-10T00:09:52.827 に答える
1

休憩が必要だったので、以下をまとめました。ただし、プラグインを作成する価値があるかどうかはわかりません。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>
            Counter
        </title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
        <script type="text/javascript">
            //<![CDATA[
                function createCounter(elementId,start,end,totalTime,callback)
                {
                    var jTarget=jQuery("#"+elementId);
                    var interval=totalTime/(end-start);
                    var intervalId;
                    var current=start;
                    var f=function(){
                        jTarget.text(current);
                        if(current==end)
                        {
                            clearInterval(intervalId);
                            if(callback)
                            {
                                callback();
                            }
                        }
                        ++current;
                    }
                    intervalId=setInterval(f,interval);
                    f();
                }
                jQuery(document).ready(function(){
                    createCounter("counterTarget",0,20,5000,function(){
                        alert("finished")
                    })
                })
            //]]>
        </script>
    </head>
    <body>
        <div id="counterTarget"></div>
    </body>
</html>
于 2010-03-29T18:43:59.153 に答える
0

jCounterを試してみてください。開始番号と終了番号を指定できる customRange 設定があり、最後に必要なフォールバックを含めてカウントアップすることもできます。

于 2012-09-26T21:54:50.360 に答える