簡體   English   中英

使視圖中的動畫功能更加靈活

[英]Make function to animate when in view more flexible

我有一些代碼可以在滾動到視圖中時為幾個數字設置動畫。 一切正常。 但是,目前它只適用於一組數字並綁定到一個 div(帶有一個 id)。 我想讓它變得更加靈活,使其適用於 1 組以上的數字。 DIV id 可以是 counter1、counter2、counter3 等。

var a = 0;
$(window).scroll(function() {
var oTop = $('#counter1').offset().top - window.innerHeight;
if (a == 0 && $(window).scrollTop() > oTop) {
$('.counter-value').each(function() {
  var $this = $(this),
    countTo = $this.attr('data-count');
...

這是筆: https : //codepen.io/anon/pen/bQWpjJ

謝謝你的幫助!

也許您可以通過首先使用$('#counter1, #counter2').each( .. )迭代每個計數器來修改您的實現。

在每次迭代中,您可以通過為該計數器實例設置window.scroll()處理程序來有效地重用現有代碼。

您還將在迭代中移動var a = 0 ,以便您的代碼跟蹤此計數器實例的唯一滾動偏移量。

最后,您要確保為迭代的當前counter實例選擇'.counter-value'元素:

 $('#counter1, #counter2').each(function() { var a = 0; var counter = $(this); $(window).scroll(function() { var oTop = counter.offset().top - window.innerHeight; if (a == 0 && $(window).scrollTop() > oTop) { $('.counter-value', counter).each(function() { var $this = $(this), countTo = $this.attr('data-count'); $({ countNum: $this.text() }).animate({ countNum: countTo }, { duration: 2000, easing: 'swing', step: function() { $this.text(Math.floor(this.countNum)); }, complete: function() { $this.text(this.countNum); } }); }); a = 1; } }); })
 .spacing { width:100%; height: 1280px; position:relative; } .counter {text-align:center} .counter-value {display:inline-block; padding:20px 40px; margin:0 20px; border:1px solid #ddd; font-family:Arial; font-size:50px; font-weight:bold}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <div class="spacing"></div> <div id="counter1"> <div class="counter-value" data-count="300">0</div> <div class="counter-value" data-count="400">100</div> <div class="counter-value" data-count="1500">200</div> </div> <div class="spacing"></div> <div id="counter2"> <div class="counter-value" data-count="500">100</div> <div class="counter-value" data-count="600">200</div> <div class="counter-value" data-count="1700">300</div> </div> <div class="spacing"></div>

這是一個有效的代碼筆- 希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM