zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

使用jq做一個數字遞增效果

數字遞增,顧名思義就是數字不斷增加,數字遞增的效果就是要一定時間內,讓數字有一個增加的特效,一般用於強調某個內容。

用 jquery 也很好處理,大概就是下面這些。

  • data-to 屬性代表最後想要遞增到的數值
  • data-speed 代表數值想要遞增的過程時間

class="num-ber"id="count-number" 按照這個填入。

<p>
  <span class="num-ber" id="count-number" data-to="40" data-speed="1000"></span>+
</p>

引入 jquery 之後再添加下面的 js 代碼。

$.fn.countTo = function (a) {
  a = a || {};
  return $(this).each(function () {
    var c = $.extend({},
      $.fn.countTo.defaults, {
        from: $(this).data("from"),
        to: $(this).data("to"),
        speed: $(this).data("speed"),
        refreshInterval: $(this).data("refresh-interval"),
        decimals: $(this).data("decimals")
      }, a);
    var h = Math.ceil(c.speed / c.refreshInterval),
      i = (c.to - c.from) / h;
    var j = this,
      f = $(this),
      e = 0,
      g = c.from,
      d = f.data("countTo") || {};
    f.data("countTo", d);
    if (d.interval) {
      clearInterval(d.interval)
    }
    d.interval = setInterval(k, c.refreshInterval);
    b(g);

    function k() {
      g += i;
      e++;
      b(g);
      if (typeof (c.onUpdate) == "function") {
        c.onUpdate.call(j, g)
      }
      if (e >= h) {
        f.removeData("countTo");
        clearInterval(d.interval);
        g = c.to;
        if (typeof (c.onComplete) == "function") {
          c.onComplete.call(j, g)
        }
      }
    }

    function b(m) {
      var l = c.formatter.call(j, m, c);
      f.html(l)
    }
  })
};
$.fn.countTo.defaults = {
  from: 0,
  to: 0,
  speed: 1000,
  refreshInterval: 100,
  decimals: 0,
  formatter: formatter,
  onUpdate: null,
  onComplete: null
};

function formatter(b, a) {
  return b.toFixed(0)
}
$("#count-number").data("countToOptions", {
  formatter: function (b, a) {
    return b.toFixed(0).replace(/\B(?=(?:\d{3})+(?!\d))/g, ",")
  }
});
$(".num-ber").each(count);

function count(a) {
  var b = $(this);
  a = $.extend({},
    a || {},
    b.data("countToOptions") || {});
  b.countTo(a)
};
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。