javascript - 在窗口滚动时触发 jQuery 动画数字计数器

标签 javascript jquery html animation

我试图让这个 jQuery 动画计数器在用户向下滚动页面超过 200 像素时立即触发:

原始 jQuery 代码来自 here

$('.Count').each(function () {
    var $this = $(this);
    jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
        duration: 1000,
        easing: 'swing',
        step: function () {
            $this.text(Math.ceil(this.Counter));
        }
    });
});

我尝试将其包装在以下 jQuery 中,但它直到最后才触发动画:

$(window).scroll(function() {
    if ($(window).scrollTop() > 200) {
        $('.Count').each(function () {
            var $this = $(this);
            jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
                duration: 1000,
                easing: 'swing',
                step: function () {
                    $this.text(Math.ceil(this.Counter));
                }
            });
        });
    }
});

HTML:

<span class="Count">100</span>
<br/>
<span class="Count">200</span>
<br/>
<span class="Count">300</span>

另一篇文章中的 fiddle 是 here

当用户滚动到 View 中或页面向下 200 像素时触发 jQuery 计数器的最佳方法是什么?我也尝试过 jQuery Wayfinder,但没有成功。

最佳答案

在触发动画之前解除滚动处理程序的绑定(bind)(使用 $(window).off("scroll")),以防止用户继续滚动时动画重新启动。

$(window).scroll(startCounter);
function startCounter() {
    if ($(window).scrollTop() > 200) {
        $(window).off("scroll", startCounter);
        $('.Count').each(function () {
            var $this = $(this);
            jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
                duration: 1000,
                easing: 'swing',
                step: function () {
                    $this.text(Math.ceil(this.Counter));
                }
            });
        });
    }
}
body {
    font-family: sans-serif;
    height: 300vh;
}
.Count {
    position: fixed;
    top: 8px;
    left: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Count">100</div>

关于javascript - 在窗口滚动时触发 jQuery 动画数字计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858421/

相关文章:

ipad - 如何让我的 HTML5 视频播放器在 iPad 上自动播放,例如 filmon.com?

php - 数据插入时自动输出数据库记录

javascript - padStart() 在 IE11 中不工作

JavaScript 数组索引

javascript - 停止 Javascript 计时器

jquery - 尝试使用 jQuery 使表格缓慢显示

html - 将多个 div 放置在没有容器 div/包装器的两列中

javascript - Batarang 正则拦截表达式

javascript - 删除以前的 "droppable"jQuery UI

javascript - 无法在 javascript jQuery 中读取 PHP 结构数组