簡體   English   中英

為什么達到目標后倒數?

[英]Why is this counting down after reaching the target?

我希望有一個僅在屏幕上實際激活的計數器。 我已經從發現的其他示例中設法做到了這一點。

HTML:

<div>Scroll Down</div>
<span class="count">200</span>

CSS:

div {
   height:800px;
   background:red;
}
h1 {
   display:none;
}

Javascript:

$(window).scroll(function() {
    var hT = $('#scroll-to').offset().top,
        hH = $('#scroll-to').outerHeight(),
        wH = $(window).height(),
        wS = $(this).scrollTop();
    console.log((hT - wH), wS);
    if (wS > (hT + hH - wH)) {
        $('.count').each(function() {
            $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
            }, {
                duration: 4000,
                easing: 'swing',
                step: function(now) {
                    $(this).text(Math.ceil(now));
                }
            });
        });
    }
});

演示:

https://jsfiddle.net/76d57vjL/

問題是,它達到200,然后倒數至0,但我希望它保持在200。盡管如此,我似乎無法弄清楚到底是什么引起的。

問題是您要創建多個動畫,因此在開始計數后返回到1,我用一個標志對其進行了修復,但可能可以用高度做一些檢查。

這是帶有標志的修復程序: https : //jsfiddle.net/uc0av8fh/

var flag = true;
$(window).scroll(function() {
$('#scroll-to');
   var hT = $('#scroll-to').offset().top,
       hH = $('#scroll-to').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
    console.log((hT-wH) , wS);
   if (wS > (hT+hH-wH)){
    $('.count').each(function () {
      if(!flag) return;
      //console.log();
      flag = false;
      $(this).prop('Counter',0).animate({
          Counter: $(this).text()
      }, {
          duration: 4000,
          easing: 'swing',
          step: function (now) {
              $(this).text(Math.ceil(now));
              return 1;
          }
      });
    });
   }
});

暫無
暫無

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

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