在一個業餘愛好項目上學習一些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動畫?
,而不是'Math.floor的animationStart(的Math.random()* 2)=== 1'你可以只使用'的Math.random()<0.5' – vahanpwns
@ user2429266感謝提示,總是讚賞。動畫是背景的一部分,所以我會很懶,不會刪除事件偵聽器。我知道資源處理很重要。 問題出現在我開始更改animationDirection之前。並且在更改屬性之前隱藏文本似乎也不起作用(不確定我是否正確隱藏了它)。 –
@vahanpwns我會用它,但是我會把它改成'>'嘿嘿。 –