小白技巧:计数动画特效jQuery插件

Posted 长安紫薯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了小白技巧:计数动画特效jQuery插件相关的知识,希望对你有一定的参考价值。

一个很棒的计数动画

计数动画特效jQuery插件

jquery.countTo.js

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
  var CountTo = function (element, options) {
    this.$element = $(element);
    this.options  = $.extend({}, CountTo.DEFAULTS, this.dataOptions(), options);
    this.init();
  };

  CountTo.DEFAULTS = {
    from: 0,               // the number the element should start at
    to: 0,                 // 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
    formatter: formatter,  // handler for formatting the value before rendering
    onUpdate: null,        // callback method for every time the element is updated
    onComplete: null       // callback method for when the element finishes updating
  };

  CountTo.prototype.init = function () {
    this.value     = this.options.from;
    this.loops     = Math.ceil(this.options.speed / this.options.refreshInterval);
    this.loopCount = 0;
    this.increment = (this.options.to - this.options.from) / this.loops;
  };

  CountTo.prototype.dataOptions = function () {
    var options = {
      from:            this.$element.data('from'),
      to:              this.$element.data('to'),
      speed:           this.$element.data('speed'),
      refreshInterval: this.$element.data('refresh-interval'),
      decimals:        this.$element.data('decimals')
    };

    var keys = Object.keys(options);

    for (var i in keys) {
      var key = keys[i];

      if (typeof(options[key]) === 'undefined') {
        delete options[key];
      }
    }

    return options;
  };

  CountTo.prototype.update = function () {
    this.value += this.increment;
    this.loopCount++;

    this.render();

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

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

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

  CountTo.prototype.render = function () {
    var formattedValue = this.options.formatter.call(this.$element, this.value, this.options);
    this.$element.text(formattedValue);
  };

  CountTo.prototype.restart = function () {
    this.stop();
    this.init();
    this.start();
  };

  CountTo.prototype.start = function () {
    this.stop();
    this.render();
    this.interval = setInterval(this.update.bind(this), this.options.refreshInterval);
  };

  CountTo.prototype.stop = function () {
    if (this.interval) {
      clearInterval(this.interval);
    }
  };

  CountTo.prototype.toggle = function () {
    if (this.interval) {
      this.stop();
    } else {
      this.start();
    }
  };

  function formatter(value, options) {
    return value.toFixed(options.decimals);
  }

  $.fn.countTo = function (option) {
    return this.each(function () {
      var $this   = $(this);
      var data    = $this.data('countTo');
      var init    = !data || typeof(option) === 'object';
      var options = typeof(option) === 'object' ? option : {};
      var method  = typeof(option) === 'string' ? option : 'start';

      if (init) {
        if (data) data.stop();
        $this.data('countTo', data = new CountTo(this, options));
      }

      data[method].call(data);
    });
  };
}));

countTo.js

    jQuery(function ($) {
      // custom formatting example
      $('#earth').data('countToOptions', {
        formatter: function (value, options) {
          return value.toFixed(options.decimals).replace(/\\B(?=(?:\\d{3})+(?!\\d))/g, ',');
        }
      });

      // custom callback when counting completes
      $('#countdown').data('countToOptions', {
        onComplete: function (value) {
          $(this).text('BLAST OFF!').addClass('red');
        }
      });

      // another custom callback for counting to infinity
      $('#infinity').data('countToOptions', {
        onComplete: function (value) {
          count.call(this, {
            from: value,
            to: value + 1000
          });
        }
      });

      // start all the timers
      $('.timer').each(count);

      // restart a timer when a button is clicked
      $('.restart').click(function (event) {
        event.preventDefault();
        var target = $(this).data('target');
        $(target).countTo('restart');
      });

      function count(options) {
        var $this = $(this);
        options = $.extend({}, options || {}, $this.data('countToOptions') || {});
        $this.countTo(options);
      }
    });

e.html

<html>
<head>
  <title>jQuery countTo Example</title>

  <style type="text/css">
    body {
      font-family: Arial;
      padding: 25px;
    }

    .example {
      position: relative;
      padding: 25px;
      margin: 25px 0;
      line-height: 1em;
      background-color: #eee;
    }

    .example h2 {
      margin-right: 100px;
    }

    .example p {
      position: absolute;
      right: 25px;
      top: 25px;
      font-size: 20px;
    }

    .red {
      color: #c00;
    }
  </style>
</head>

<body>
  <h1>jQuery countTo Example</h1>
  <p>
    This is a simple example of the
    <a href="https://github.com/mhuggins/jquery-countTo">jQuery countTo plugin</a>
    created by <a href="http://www.matthuggins.com">Matt Huggins</a>.  Refer to
    the full documentation for more usage information.
  </p>

  <div class="example">
    <h2>
      How many licks to the center of a Tootsie Pop?
      <button class="restart" data-target="#lollipop">Restart</button>
    </h2>
    <p><b class="timer" id="lollipop" data-to="3" data-speed="1500"></b></p>
  </div>

  <div class="example">
    <h2>
      What is Earth's radius?
      <button class="restart" data-target="#earth">Restart</button>
    </h2>
    <p><b class="timer" id="earth" data-to="3968" data-speed="10000"></b> miles</p>
  </div>

  <div class="example">
    <h2>
      Start the countdown...
      <button class="restart" data-target="#countdown">Restart</button>
    </h2>
    <p>Lift-off in <b class="timer" id="countdown" data-from="3" data-to="1" data-speed="3000"></b></p>
  </div>

  <div class="example">
    <h2>
      Earth's Gravity
      <button class="restart" data-target="#gravity">Restart</button>
    </h2>
    <p><b class="timer" id="gravity" data-from="0" data-to="9.8" data-speed="3000" data-decimals="2"></b> m/s<sup>2</sup></p>
  </div>

  <div class="example">
    <h2>
      To infinity...and beyond!
      <button class="restart" data-target="#infinity">Restart</button>
    </h2>
    <p><b class="timer" id="infinity" data-from="0" data-to="1000" data-speed="800"></b></p>
  </div>

  <script type="text/javascript" src="../jquery.min.js"></script>
  <script type="text/javascript" src="jquery.countTo.js"></script>
  <script type="text/javascript" src="countTo.js"></script>
</body>
</html>

以上是关于小白技巧:计数动画特效jQuery插件的主要内容,如果未能解决你的问题,请参考以下文章

40款经典前端特效插件---分享

人人必知的10个jQuery小技巧

前端小白案例-爱新鲜抽屉式特效制作

前端数字上涨动画特效

18款js和jquery文字特效代码分享

利用jQuery实现输入文字弹幕显示动画特效