在播放动画之前,等待元素出现在视图中 [英] Wait for Element to be in View before Playing Animation

查看:59
本文介绍了在播放动画之前,等待元素出现在视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些适用于加载栏的Jquery,但我希望加载栏直到它在视图内时才填充,反正有这样做吗?如果需要CSS,HTML或当前加载栏的jsfiddle示例,请在下面控制加载栏的Jquery告诉我.任何帮助是极大的赞赏!

I have some Jquery that applies to a loading bar but I'd like the loading bar not to fill until its within view, is there anyway to do this? Th Jquery that controls the loading bar is below, if you need the CSS, HTML, or a jsfiddle example of the current loading bar let me know. Any help is greatly appreciated!

  $('.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);
    }
  });
});

推荐答案

我之前写过类似的计数器代码并根据需要进行更改,这是一个代码,每个元素仅在屏幕上出现时就开始动画:

I had written a similar code for counters before and change it as you want, this is a code that each element start an animation just when appear on screen:

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.
  });
}

iscodeVisible 函数帮助查找是否在每次滚动后在屏幕上出现一个控件.

The isElementVisible function help to find out is a control appeared on the screen after every scroll or not.

然后在每次滚动时调用此函数,如果显示 .bar 元素,则仅使用 startAnimation 函数对此元素启动动画.

Then you call this function on every scroll and if a .bar element appears on display, then start animation ONLY for THIS element using the startAnimation function.

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

The !$(this).hasClass('Starting') is added to code to prevent unwanted call function, when an animation start for first time, the Starting class is added to element and is skipped in next times.

实际操作: >>> JSFiddle

See in Action: >>> JSFiddle

这篇关于在播放动画之前,等待元素出现在视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆