我创建了一个一开始就很好用的计数器。基本上,当您滚动到某个点时,计数器会开始设置动画。但是,对于大于或等于1000的数字没有逗号。因此,当我尝试将等于或大于1000的整数放入“逗号”后,问题就开始出现。初始计数器完成后,当您向下或向上滚动时,尽管动画已完成,但计数器又开始重新设置动画。我尝试了所有尝试修复它的方法,包括使用“ .stop()”和“ .finish()”,但均无法正常工作。
有什么建议吗?
jQuery(document).ready(function($) {
"use strict";
$(document).scroll(function() {
var y = $(this).scrollTop();
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/\B(?=(\d{3})+(?!\d))/g, ",") );
});
};
var countTo1 = $('#counter1').attr('data-count');
var countTo2 = $('#counter2').attr('data-count');
var countTo3 = $('#counter3').attr('data-count');
if (y > 30) {
$({countNum: $('#counter1').text()}).animate({countNum: countTo1}, {
duration: 1000,
easing:'linear',
decimals: 0,
step: function() {
$('#counter1').text(Math.floor(this.countNum)).digits();
},
complete: function() {
$('#counter1').text(this.countNum);
$('#counter1').digits();
}
});
$({countNum: $('#counter2').text()}).animate({countNum: countTo2}, {
duration: 1000,
easing:'linear',
step: function() {
$('#counter2').text(Math.floor(this.countNum));
},
complete: function() {
$('#counter2').text(this.countNum);
}
});
$({countNum: $('#counter3').text()}).animate({countNum: countTo3}, {
duration: 1000,
easing:'linear',
step: function() {
$('#counter3').text(Math.floor(this.countNum));
},
complete: function() {
$('#counter3').text(this.countNum);
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> </p><p> </p><p> </p><p> </p><p> </p><p> </p><p> </p>
<div class="content-module three-column module stat-number-block">
<div class="row">
<div class="small-12 columns">
</div>
<div class="small-12 medium-4 columns content ">
<h3 style="" class="subhead"><span id="counter1" data-count="1400">0</span> +</h3> <p style="text-align: center;"><strong>Successful weight loss surgeries</strong></p>
</div>
<div class="small-12 medium-4 columns content ">
<h3 style="" class="subhead"><span id="counter2" data-count="100"> 0 </span>k +</h3> <p style="text-align: center;"><strong>Pounds shed across all patients</strong></p>
</div>
<div class="small-12 medium-4 columns content ">
<h3 style="" class="subhead"><span id="counter3" data-count="98"> 0 </span>% </h3> <p style="text-align: center;"><strong>Of patients see resolution of sleep apnea, diabetes, and more</strong></p>
</div>
</div>
</div>