【问题标题】:Wait for Element to be in View before Playing Animation在播放动画之前等待元素出现在视图中
【发布时间】:2014-09-28 14:51:28
【问题描述】:

我有一些适用于加载栏的 Jquery,但我希望加载栏在视图内之前不要填​​充,有没有办法做到这一点?下面是控制加载栏的 Jquery,如果您需要当前加载栏的 CSS、HTML 或 jsfiddle 示例,请告诉我。任何帮助是极大的赞赏!

  $('.bar-percentage[data-percentage]').each(function () {
  var progress = $(this);
  var percentage = Math.ceil($(this).attr('data-percentage'));
  $({countNum: 0}).animate({countNum: percentage}, {
    duration: 2000,
    easing:'swing',
    step: function() {
      // What todo on every count
    var pct = '';
    if(percentage == 0){
      pct = Math.floor(this.countNum) + '%';
    }else{
      pct = Math.floor(this.countNum+1) + '%';
    }
    progress.text(pct) && progress.siblings().children().css('width',pct);
    }
  });
});

【问题讨论】:

标签: jquery html css animation delay


【解决方案1】:

我之前写了一个similar code for counters 并根据需要更改它,这是每个元素在屏幕上出现时开始动画的代码:

function isElementVisible($elementToBeChecked)
{
    var TopView = $(window).scrollTop();
    var BotView = TopView + $(window).height();
    var TopElement = $elementToBeChecked.offset().top;
    var BotElement = TopElement + $elementToBeChecked.height();
    return ((BotElement <= BotView) && (TopElement >= TopView));
}

$(window).scroll(function () {
    $( ".bar" ).each(function() {
        $this = $(this);
        isOnView = isElementVisible($(this));
        if(isOnView && !$(this).hasClass('Starting')){
            $(this).addClass('Starting');
            startAnimation($(this));
        }
    });
});

function startAnimation($this) {
  $this.animate({
    width: "100%"
  }, 3000, function() {
    // Animation complete.
  });
}

isElementVisible函数帮助判断每次滚动后屏幕上是否出现一个控件。

然后在每次滚动时调用此函数,并且如果显示屏上出现 .bar 元素,则使用 startAnimation 函数仅为此元素启动动画。

!$(this).hasClass('Starting') 被添加到代码中以防止不必要的调用函数,当动画第一次开始时,Starting 类被添加到元素中并在下次跳过。

见效: >>> JSFiddle

【讨论】:

  • 我对 jQuery 不是很熟悉,如何将它与我当前的 jQuery 合并?我知道我会把我的动画放在哪里,但我的动画不是一个简单的 this.animate
  • 你不需要修改前两个块,只需为你想要动画的元素设置.bar类,并将你的主要代码放在startAnimation函数中。当元素出现在屏幕上时会调用此函数,因此当它出现在startAnimation 函数中时,请执行您想要的操作。您没有提供完整的代码,也没有提供 JSFiddle,获得确切答案的期望非常高。虽然我认为这是一个非常接近和干净的答案,但您可能找不到更好的答案。
猜你喜欢
  • 2021-12-21
  • 1970-01-01
  • 2014-10-15
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
相关资源
最近更新 更多