繁体   English   中英

jQuery 计数器 - 整数或小数

[英]jQuery Counter - Whole Numbers or Decimals

我正在使用这个 jQuery 脚本来显示一个计数器。 我需要同时显示整数和小数,但我似乎无法确定哪个是哪个。

 jQuery('.counter-wrap.count').each(function() { jQuery(this).prop('Counter', 0).animate({ Counter: jQuery(this).attr('data-count') }, { duration: 1000, easing: 'swing', step: function(now) { jQuery(this).text( Math.round(this.Counter, 0) == this.Counter? this.Counter: this.Counter.toFixed(1)); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="counter-wrap"> <h2><span class="count" data-count="6.8">0</span>M</h2> </div> <div class="counter-wrap"> <h2><span class="count" data-count="5.2">0</span>M</h2> </div> <div class="counter-wrap"> <h2><span class="count" data-count="90">0</span></h2> </div>

请检查我的小提琴

当原始值中包含一个时,仅四舍五入到小数位,您需要询问该值,而不是Counter属性,以查看它是否具有浮点数。

还要注意示例中data()方法的使用,以避免强制任何数据类型:

 jQuery($ => { $('.counter-wrap.count').each(function() { $(this).prop('Counter', 0).animate({ Counter: $(this).data('count') }, { duration: 1000, easing: 'swing', step: function(now) { $(this).text(this.Counter.toFixed($(this).data('count') % 1 === 0? 0: 1)); } }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="counter-wrap"> <h2><span class="count" data-count="6.8">0</span>M</h2> </div> <div class="counter-wrap"> <h2><span class="count" data-count="5.2">0</span>M</h2> </div> <div class="counter-wrap"> <h2><span class="count" data-count="90">0</span></h2> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM