Javascript 当 Div 可见时

Javascript When Div is Visible

我希望计数器仅在 div 被查看后才开始计数。这将位于网站页面的下方,因此如果它开始动画化,访问者将看不到它。

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

.wording {float: left}

.spacer {height: 1000px; width: 300px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="wording">
Positive
Number: <br></div>

<span class="count">99</span><span class="percent">%</span>

<div class="spacer"> wait

</div>

<span class="count">99</span><span class="wording">%</span>

当滚动位置到达计数器元素并显示在屏幕上时,您需要使用 scroll 事件来 运行 计数器。

var counterDone = false;

$(window).scroll(function(){
    var elemPosTop = $(".count").position().top;
    var elemHeight = $(".count").height();
    var winScroTop = $(window).scrollTop();
    var winHeight = $(window).height();
    
    if (elemPosTop < winScroTop + winHeight - elemHeight)    
        counterDone = (counterDone == false) ? counter() : true;     
})
 
function counter(){
    $('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 4000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
}
.spacer {
    height: 1000px; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="spacer">Go to down</div>

<span>Counter: </span>
<span class="count">100</span>
<span class="percent">%</span>

<div class="spacer"></div>