验证条件在滚动时满足,然后仅运行一次函数



我的代码可以运行计数器,从0到由HTML标签内部的文本定义的图。这很好 - 我有四个元素使用该类,每个元素都会从0时从0计数。

但是棘手的是,我希望各自的计数器在每个元素进入视图时开始。

我发现的是,当我滚动时,柜台一直在重新启动。我已经尝试使用.scroll()事件处理程序附加的jQuery .one()方法,但是我需要不断检查条件是否对可见元素感到满意,这就是我来不及的地方。

这就是我所拥有的:

$(window).on('scroll',function(e) {
    $('.count').each(function(i) {      
        var topOfElement = $(this).offset().top;
        var bottomOfWindow = $(window).scrollTop() + $(window).height();
        if (bottomOfWindow > topOfElement) {
            $(window).one('scroll',function(e) {    
                $(this).prop('Counter',0).animate({
                    Counter: $(this).text()
                }, {
                    duration: 2000,
                    easing: 'swing',
                    step: function (now) {
                        $(this).text(Math.ceil(now));
                    }
                });
            });
        }
    });
});

和简单的html:

<span class="count">4143</span>
<span class="count">920</span>
<span class="count">5112</span>
<span class="count">76</span>

我得到了"无法读取属性的'createCumentFragment'doffined"错误"错误。

正如Epascarello指出的那样,您正在重新绑定每个.croll事件上的.Croll事件。您只需要一个绑定。

但是您还需要一种方法来识别计数过程已经启动,并且不必再次运行。简单的方法是将类添加到元素中。

我也看不出您是如何从跨度标签中获得最大值的。

$(window).on('scroll',function(e) {
    $('.count').each(function(i, e) {      
        var topOfElement = $(e).offset().top;
        var bottomOfWindow = $(window).scrollTop() + $(window).height();
        if (bottomOfWindow > (topOfElement + 80)) {
        //debugger;
            if ( !$(e).hasClass('done') ){
                $(e).addClass('done');
                let maxcnt = $(e).text();
                maxcnt = parseInt(maxcnt);
                $(e).prop('Counter',0).animate({
                    Counter: $(e).text()
                }, {
                    duration: 2000,
                    easing: 'swing',
                    step: function (maxcnt) {
                        $(e).text(Math.ceil(maxcnt));
                    }
                });
            }
        }
    });
});
div{height:250px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div></div>
<span class="count">4143</span>
<div></div>
<span class="count">920</span>
<div></div>
<span class="count">5112</span>
<div></div>
<span class="count">76</span>
<div></div>

一个滚动中的 this是窗口元素。

$('.count').each(function(i) {      
  var elem = $(this);
  ...
  if (bottomOfWindow > topOfElement) {
    $(window).one('scroll',function(e) {
      $(elem).prop('Counter',0).animate({
        ...

最新更新