首頁  >  文章  >  web前端  >  js實作數字遞增特效實例程式碼

js實作數字遞增特效實例程式碼

怪我咯
怪我咯原創
2017-07-06 11:34:423256瀏覽

本篇文章主要介紹了js實現仿支付寶我的財富裡的數字遞增特效,具有很好的參考價值。下面跟著小編一起來看下吧

上週五應著公司臨時需求,一天的時間解決掉官網(ps:比較簡單哈哈),需求裡面有一個特效就是數字遞增到指定的數值,其實JS寫也不複雜的,但我發現一個js小插件,這個插件輕巧簡單,用起來也非常簡單實用。在這裡分享給小盆友們吧,喜歡的直接拿走。

上面就是這個外掛的效果,我們來看看怎麼使用的吧

第一: HTML部分這裡簡單列舉一個

 <p class="counter col_fourth">
  <h2 class="timer count-title" id="count-number" data-to="300" data-speed="1500"></h2>
  <p class="count-text ">小月博客</p>
 </p>

上面我們來了解兩個關鍵的東西:

  • #data-to   這個屬性控制你最終要遞增的數值是多少

  • #data-speed    這個看英文的意思就很清楚了就是表示資料遞增的速度了

ps: 這裡的class和id  依照大家各自的修改去調整就好了,

第二: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(2)
}
$("#count-number").data("countToOptions", {
  formatter: function(b, a) {
   return b.toFixed(2).replace(/\B(?=(?:\d{3})+(?!\d))/g, ",")
  }
});
$(".timer").each(count);
function count(a) {
  var b = $(this);
  a = $.extend({},
  a || {},
  b.data("countToOptions") || {});
  b.countTo(a)
};

以上就是程式碼的全部了,css部分就不在這裡顯示了,demo下載的小夥伴在下面點擊下載吧!

其實這個外掛程式可擴充性很大的,至於小夥伴喜歡什麼樣子的顯示自己動手改造吧!

以上是js實作數字遞增特效實例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn