HTMLの書き方
body内のカウントアップ・ダウンを表示させたい場所にHTMLを記載します。
<div id="box1" class="box"><!--画面に入ったら数字を動かす基点にするためのid を付与-->
<p>男性の学生数<br><span class="count-up count-size">2540</span>人</p><!-- count-up ← カウントアップ用class名-->
<!--/box--></div>
<div id="box2" class="box"><!--画面に入ったら数字を動かす基点にするためのid を付与-->
<p>学食充実満足度全国<br>第<span class="count-down count-size">1</span>位</p><!-- count-down ← カウントダウン用class名-->
<!--/box--></div>
body 終了タグ直前にjQuery、jquery.inview、動きを制御する自作のJS の3つを読み込みます。
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/protonet-jquery.inview/1.1.2/jquery.inview.min.js"></script>
<!--自作のJS-->
<script src="js/9-5-1.js"></script>
JSの書き方
//box1の指定
$('#box1').on('inview', function(event, isInView) {
if (isInView) {
//要素が見えたときに実行する処理
$("#box1 .count-up").each(function(){
$(this).prop('Counter',0).animate({//0からカウントアップ
Counter: $(this).text()
}, {
// スピードやアニメーションの設定
duration: 2000,//数字が大きいほど変化のスピードが遅くなる。2000=2秒
easing: 'swing',//動きの種類。他にもlinearなど設定可能
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
});
//box2の指定
$('#box2').on('inview', function(event, isInView) {
if (isInView) {
//要素が見えたときに実行する処理
$("#box2 .count-down").each(function(){
$(this).prop('Counter',10).animate({//10からカウントダウン
Counter: $(this).text()
}, {
// スピードやアニメーションの設定
duration: 1000,//数字が大きいほど変化のスピードが遅くなる。1000=1秒
easing: 'swing',//動きの種類。他にもlinearなど設定可能
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
}
});