2016-04-09 35 views
0

在一个业余爱好项目上学习一些html,css和js。CSS动画行为怪异

一直试图解决一个CSS动画行事怪异的问题。在第一次迭代之后,它有时在动画的中间出现或消失,而在其他时候,它只是闪烁而快速。一直在多个浏览器和多台计算机/设备上尝试,结果都一样。

JSFiddle here(部分代码已删除)和现场示例here

的index.html

... 
<body onload="init()"> 
<div class="leftanimation">Cool Gliding Text</div> 
<div class="leftanimation">Lorem Ipsum Dolor Sit</div> 
<div class="leftanimation">How Cool Is This?</div> 
<div class="leftanimation">Wwiiiieeee! </div> 
<div class="leftanimation">Sssssswwwwoooosssshhh!</div> 
<div class="leftanimation">Drive by text!</div> 
<div class="leftanimation">More example text ...</div> 
<div class="leftanimation">Last test text.</div> 
... 

的script.js

function init() { 

    var a = document.getElementsByClassName("leftanimation"); 

    for (i = 0; i < a.length; i++){ 
     a[i].addEventListener("animationiteration", updateAnim); 
    } 
} 

function updateAnim() { 

    this.style.left = Math.random() * 7 + "%"; 
    //this.style.transform = "rotate(-90deg) translate(0px, " + Math.random() * 50 + 10 + "px)"; 
    this.style.fontSize = Math.floor(Math.random() * 100) + 30 + "px"; 
    this.style.opacity = Math.random() * 0.5; 
    this.style.animationDuration = Math.floor(Math.random() * 30) + 20 + "s"; 
    if (Math.floor(Math.random() * 2) == 1) { 
     this.style.animationDirection = "normal"; 
    } else { 
     this.style.animationDirection = "reverse"; 
    } 
} 

的style.css

.leftanimation { 
    position: fixed; 
    transform: rotate(-90deg); 
    transform-origin: 5% 50%; 
    animation: glide 0.01s infinite; 
    animation-direction: alternate; 
    backface-visibility: hidden; 
    white-space: nowrap; 
    opacity: 0; 
    font-size: 20px; 
    z-index: -2; 
} 

@keyframes glide { 
    0% { top: -150%; animation-timing-function: ease-in-out; } 
    100% { top: 250%; animation-timing-function: ease-in; } 
} 

任何想法WH它的行为是这样吗?

更新

怪异的行为似乎消失了,如果我从updateAnim()删除animationDuration。但是,这并不能解决我的问题,因为我希望动画是随机的。
也许它只是太多处理的CSS动画?

回答

0

只是一些提示:如果您使用addEventListener(),您应该将它们收集在一个数组中,以便在需要时将其删除。

var eventListener = []; 
element.addEventListener(event,callback,false); 
eventListener.push([element,event,callback]); 

要删除它们只是循环阵列上:

while(var current = eventListener.pop()){ 
    current[0].removeEventlistener(current[1],current[2]); 
} 

这仅仅是学习它从一开始。

和:

Math.floor(Math.random() * 2) == 1 

应该

Math.floor(Math.random() * 2) === 1 

如果我看到纠正你的问题设置animationDirection时发生。它将状态切换为由css给定的默认状态,然后以颠倒顺序运行新动画。

尝试隐藏元素并设置动画开始位置的起始位置。之后显示元素并开始动画。也许包裹内的

setTimeout(function(){ 
    // setAnimationProperty etc 
},0); 
+0

,而不是'Math.floor的animationStart(的Math.random()* 2)=== 1'你可以只使用'的Math.random()<0.5' – vahanpwns

+0

@ user2429266感谢提示,总是赞赏。动画是背景的一部分,所以我会很懒,不会删除事件侦听器。我知道资源处理很重要。 问题出现在我开始更改animationDirection之前。并且在更改属性之前隐藏文本似乎也不起作用(不确定我是否正确隐藏了它)。 –

+0

@vahanpwns我会用它,但是我会把它改成'>'嘿嘿。 –