簡體   English   中英

奇怪的CSS動畫

[英]CSS animations acting weird

在一個業余項目中學習一些html,css和js。

試圖解決一個奇怪的css動畫問題。 第一次迭代后,它有時會在動畫中間出現或消失,而有時它只是快速閃爍。 在多種瀏覽器和多種計算機/設備中進行嘗試時,所有結果均相同。

這里是 JSFiddle(已刪除了一些代碼), 這里是實況示例。

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

任何想法,為什么它會這樣?

更新資料

如果我從updateAnim()刪除animationDuration ,奇怪的行為似乎消失了。 但是,這不能解決我的問題,因為我希望動畫隨機化。
也許對於CSS動畫來說處理太多了?

只是一些技巧:如果使用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給定的默認狀態,然后以相反的順序運行新動畫。

嘗試隱藏元素並設置動畫應從其開始的開始位置。 之后,顯示元素並開始動畫。 也許將animationStart包裝在一個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM