jquery数字滚动

这篇博客介绍了一个使用jQuery实现的数字动态计数动画插件。通过设置`data-from`、`data-to`、`data-speed`等属性,可以自定义计数的起始值、结束值和动画速度。代码中还定义了`formatter`函数,用于格式化显示的数字,支持小数点后的位数控制。此外,动态赋值后需要调用`.each(count)`重新渲染计数器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!-- 需要加class .itmer,  data-from 为 开始数值 不填默认从0开始 data-to  
      data-speed 动画时间单位 毫秒 -->
<h2 class="timer" data-from="100" data-to="300" data-speed="1500"></h2>

方法

$.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)
} */
function formatter(b, a) {
	if(a.to.toString().indexOf('.') != -1){
		return b.toFixed(a.to.toString().split(".")[1].length);
	}
	else{
		return b.toFixed();
	}
}
$("#count-number").data("countToOptions", {
    formatter: function(b, a) {
        return b.toFixed().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",")
    },
	// toFixed(2) 小数点后2位
});
//所有的都需要加上class =“timer” 然后$(".timer").each(count);动态加载
$(".timer").each(count);
function count(a) {
    var b = $(this);
    a = $.extend({},
    a || {},
    b.data("countToOptions") || {});
    b.countTo(a)
};

动态赋值之后需要 $(".timer").each(count); 重新渲染一下,可以按区域渲染 例如 $(" #main .timer").each(count); ID为 main 下面的数据渲染

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值