ページ内にある複数の要素を、カウントアップして指定の数値に来たらストップさせるものを作ったのですが、
ページスクロールで要素が近くに来たらカウントアップをスタートさせるように書き換えたところ、
カウントアップしている数字の表示がおかしくなり、
一瞬カウントダウンしてまたカウントアップしたりするようになってしまいました。
正常にカウントアップさせるにはどのようにしたらいいのか、ご教授お願いします。
html
1<div class="count count-slow" data-num="80">00</div> 2<div class="count count-fast" data-num="20">00</div> 3<div class="count count-slow" data-num="99">00</div> 4<div class="count count-fast" data-num="8">0</div> 5<div class="count count-slow" data-num="5">0</div> 6<div class="count count-fast" data-num="40">00</div>
jQuery
1$('.count').each(function(){ 2 var self = $(this), 3 thisPosition = self.offset().top, 4 scroll = $(window).scrollTop(), 5 windowHeight = $(window).height(), 6 countMax = self.attr('data-num'), 7 thisCount = self.text(), 8 countTimer; 9 10 11 if (scroll >= thisPosition - windowHeight + windowHeight / 5){ 12 if (self.hasClass('count-slow')) { 13 var countSpeed = 600; 14 } else if (self.hasClass('count-fast')) { 15 var countSpeed = 30; 16 } 17 18 function timer(){ 19 countTimer = setInterval(function(){ 20 var countNext = thisCount++, 21 addZero = ('0' + countNext).slice(-2); 22 23 if (countMax > 10 && countNext < 10) { 24 self.text(addZero); 25 } else { 26 self.text(countNext); 27 } 28 29 if (countNext == countMax){ 30 clearInterval(countTimer); 31 } 32 }, countSpeed); 33 } 34 timer(); 35 } 36});
https://teratail.com/questions/157023この質問と内容が同じです。teratailは質問内容の編集ができるので、変更がある場合は新しい質問をするのではなく編集してください。また、こちらの質問を削除されるよう運営に連絡されることをお勧めします。https://teratail.com/contact/input