2016-04-05 13 views
2

我想在滾動我的HTML文件併到達特定節時對文本進行計數。代碼如下所示:當在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; 
      } 
     }) 

回答

0

問題是因爲你的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> 
+0

這是行得通的,但是如果我把它放在一個有條件的語句中,代碼就會計算出來,但是之後開始倒計時......我嘗試返回false但它沒有工作....請檢查我的第一篇文章爲代碼... – 151RUM

0

如果您想要像使用函數或JSON中的鍵值創建數組那樣操作,您必須將數值分配給元素。

+2

歡迎來到SO,但請提供您的答案的例子或提供一個參考鏈接,以更好地瞭解 –

0

請檢查這段代碼,你真的想要這樣嗎? 並讓我知道!

<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」屬性。

Counter: $(this).html().length 
+0

嗨Gaurav,謝謝你的建議。不幸的是,.match(/ \ d/g).length和.html()。長度不會輸出正確的數字/字符串。 – 151RUM

+0

Hi @ 151RUM你真的想要統計「count」類字符串中的字符數嗎? –

+0

不,我想動畫的計數類的內容,例如40.000單位的東西,然後它應該在4秒內計數從零到40000當達到HTML文件中的內容...你得到它的隊友? :) – 151RUM

相關問題