[英]Animate Number and Text when reach a certain point in the HTML file
向下滾動HTML文件並到達某個部分時,我想對帶有文字的數字進行計數。 代碼如下:
<h3 class="count">25 Years</h3>
<p>On the Road...</p>
<h3 class="count">143 Million</h3>
<p>Transactions worldwide 2015</p>
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
問題是,僅輸入數字時,我只會得到正確的結果。 如果我輸入25 Years
這樣的字符串,它將輸出NaN
。
對我的代碼有什么建議嗎?
var targetOffset = $(".company-numbers").offset().top;
var $w = $(window).scroll(function(){
if ( $w.scrollTop() > targetOffset ) {
(function () {
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
return false;
}
});
});
})();
} else {
return false;
}
})
問題是因為您的jQuery代碼期望該值能夠被解析為整數。 嘗試將要計數的值放在自己的元素中,例如<span>
,然后在這些值上調用jQuery邏輯。
<h3><span class="count">25</span> Years</h3>
<p>On the Road...</p>
<h3><span class="count">143</span> Million</h3>
<p>Transactions worldwide 2015</p>
如果要像在函數或JSON中創建具有鍵值的數組那樣操作,則必須為元素分配數字值。
請檢查此代碼,您真的要這樣嗎? 讓我知道!!!
<h3 class="count">25 Years</h3>
<p>On the Road...</p>
<h3 class="count">143 Million</h3>
<p>Transactions worldwide 2015</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text().match(/\d/g).length
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
</script>
或者,如果您想計算字符總數,請更改“計數器”屬性。
Counter: $(this).html().length
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.