在播放动画之前等待元素进入视图

时间:2014-08-05 20:03:41

标签: jquery html css animation delay

我有一些适用于加载栏的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);
    }
  });
});

1 个答案:

答案 0 :(得分:3)

我之前写过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元素启动动画。

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

见行动: >>> JSFiddle