添加类不起作用时的动画

时间:2014-03-27 19:35:51

标签: jquery css3 jquery-animate hide show

我有一个JQuery和CSS3代码段来创建“滚动到视图动画”。除非动画类具有可见类,否则它不会启动动画。不断发生的是它增加了类可见,但动画不会触发。我已经在所有浏览器中对此进行了测试,并且唯一似乎正确执行此操作的是Safari。我想让这个跨浏览器兼容。任何帮助都会很棒!

以下是代码段的小提琴:http://jsfiddle.net/M6VLL/

这是JS:

(function(e){e.fn.visible=function(t,n,r){var i=e(this).eq(0),s=i.get(0),o=e(window),u=o.scrollTop(),a=u+o.height(),f=o.scrollLeft(),l=f+o.width(),c=i.offset().top,h=c+i.height(),p=i.offset().left,d=p+i.width(),v=t===true?h:c,m=t===true?c:h,g=t===true?d:p,y=t===true?p:d,b=n===true?s.offsetWidth*s.offsetHeight:true,r=r?r:"both";if(r==="both")return!!b&&m<=a&&v>=u&&y<=l&&g>=f;else if(r==="vertical")return!!b&&m<=a&&v>=u;else if(r==="horizontal")return!!b&&y<=l&&g>=f}})(jQuery)

jQuery(window).scroll(function(event) {

  jQuery(".animated").each(function(i, el) {
    var el = jQuery(el);
    if (el.visible(true)) {
      el.addClass("visible"); 
    }
  });

});

这是CSS:

.animated { opacity: 0;}
.animated.visible {
  -webkit-animation-duration: 2s;
  animation-duration: 2s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  opacity: 1;
}
@-webkit-keyframes slideInLeft {
  0% {
    opacity: 0;
    -webkit-transform: translateX(-2000px);
    transform: translateX(-2000px);
  }

  100% {
    -webkit-transform: translateX(0);
    transform: translateX(0);
  }
}

@keyframes slideInLeft {
  0% {
    opacity: 0;
    -webkit-transform: translateX(-2000px);
    -ms-transform: translateX(-2000px);
    transform: translateX(-2000px);
  }

  100% {
    -webkit-transform: translateX(0);
    -ms-transform: translateX(0);
    transform: translateX(0);
  }
}

.slideInLeft {
  -webkit-animation-name: slideInLeft;
  animation-name: slideInLeft;
}

2 个答案:

答案 0 :(得分:2)

您可以使用开发工具查看问题所在。

您最初设置:

.slideInLeft {
    -webkit-animation-name: slideInLeft;
    animation-name: slideInLeft;
}

你的想法是,这不会做任何事情,因为你没有设置其余的属性。

但是,如果您查看真实属性(使用开发工具),您将看到其余属性设置为

-webkit-animation-delay: 0s;
-webkit-animation-direction: normal;
-webkit-animation-duration: 0s;
-webkit-animation-fill-mode: none;
-webkit-animation-iteration-count: 1;
-webkit-animation-name: slideInLeft;
-webkit-animation-play-state: running; 

这意味着动画已经在运行!!

当您设置.visible类时,您会更改一些动画属性,但为时已晚,动画已经完成。

答案 1 :(得分:1)

您不需要动画,只需使用过渡。我也会使用translateX(-100%)而不是你拥有的东西,所以你确定它会达到必要的数量而且不会超出它的范围。要使其跨浏览器,您只需添加其他前缀。当页面向上或向下滚动时,我还使用else语句使其返回默认位置

Demo