首页 > 解决方案 > Javascript:在滚动上做动画

问题描述

我有简单的代码,当页面加载时动画开始。当我在这个 div 上滚动时,是否有任何选项如何开始动画?

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 3000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="shiva"><span class="count">200</span></div>

标签: javascripthtml

解决方案


使用 onscroll 事件计算窗口和元素之间的距离:

$(window).on('scroll',function () {
    $('.count').each(function () {
        var wst=$(window).scrollTop();
        var wh=$(window).height();
        var dot=$(this).offset().top;
        var dh=$(this).height();
        if((dot-wst>0)&&(dot-wst<=wh-dh)&&(!$(this).hasClass("animate-complete"))){
            $(this).addClass("animate-complete");
            $(this).prop('Counter',0).animate({
                Counter: $(this).text()
            }, {
                duration: 3000,
                easing: 'swing',
                step: function (now) {
                    $(this).text(Math.ceil(now));
                }
            });
         }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="shiva"><span class="count">200</span></div>


推荐阅读