2016-04-09 39 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我會用它,但是我會把它改成'>'嘿嘿。 –