2016-04-29 12 views
2

私は最大値(HTMLで書かれた値)を表示し、ページの本文をクリックすると最大値を得るために1ずつ増加するjquery数カウンタを作成しました。しかし、ページが読み込まれると、数値は常に最大値に表示されます。私は最初にロードするときに番号が0に等しくなるようにします。ここに私のコードです:最大値ではなく0からカウンタを開始するにはどうすればよいですか?

HTML

<div class="mydiv"><span class="count">100</span></div> 
<div class="mydiv"><span class="count">200</span></div> 
<div class="mydiv"><span class="count">300</span></div> 

CSS

.mydiv { 
    width:100px; 
    height:100px; 
    background:red; 
    -moz-border-radius:50px; 
    -webkit-border-radius:50px; 
    border-radius:50px; 
    float:left; 
    margin:5px; 
} 

.count { 
    line-height:100px; 
    color:white; 
    margin-left:30px; 
    font-size:25px; 
} 

JS

$(document).ready(function(){ 
    $(window).click(function(){ 
     $('.count').each(function() { 
      $(this).prop('Counter',0).animate({ 
       Counter:$(this).text() 
      }, { 
       duration:4000, 
       easing:'swing', 
       step:function (now) { 
        $(this).text(Math.ceil(now)); 
       } 
      }); 
     }); 
    }); 
}); 

私はデモを与えています。

答えて

3

data-属性を使用して、html以外の最大値を設定します。そして、あなたは0

$(document).ready(function() { 
 
    $(window).click(function() { 
 
    $('.count').each(function() { 
 
     $(this).prop('Counter', 0).animate({ 
 
     Counter: $(this).data('limit') 
 
     }, { 
 
     duration: 4000, 
 
     easing: 'swing', 
 
     step: function(now) { 
 
      $(this).text(Math.ceil(now)); 
 
     } 
 
     }); 
 
    }); 
 
    }); 
 
});
.mydiv { 
 
    width: 100px; 
 
    height: 100px; 
 
    background: red; 
 
    -moz-border-radius: 50px; 
 
    -webkit-border-radius: 50px; 
 
    border-radius: 50px; 
 
    float: left; 
 
    margin: 5px; 
 
} 
 

 
.count { 
 
    line-height: 100px; 
 
    color: white; 
 
    margin-left: 30px; 
 
    font-size: 25px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div class="mydiv"><span class="count" data-limit="100">0</span></div> 
 
<div class="mydiv"><span class="count" data-limit="200">0</span></div> 
 
<div class="mydiv"><span class="count" data-limit="300">0</span></div>

DEMO

としてHTMLを設定することができます
関連する問題