【问题标题】:How to play one css anmation before chaging innerHTML and another one after it?如何在更改innerHTML之前播放一个css动画,然后再播放另一个?
【发布时间】:2021-03-12 08:37:06
【问题描述】:

我需要的是:当我点击按钮时,我希望旧文本慢慢消失,然后我希望新文本慢慢出现。

但消失动画永远不会播放。这是我的代码:

css

.quote-container {
    opacity: 0;
}

.appear {
    opacity: 0;
    animation: fadeIn 1200ms ease-in forwards;
}

.disappear {
    opacity: 1;
    animation: fadeOut 1200ms ease-in;
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

@keyframes fadeOut {
    from {
        opacity: 1;
    }

    to {
        opacity: 0;
    }
}

javascript

let pickARandomQuote = () => {
    index = Math.floor(Math.random() * quotes.length);
    currentQuote = quotes[index].quote;
    currentAuthor = quotes[index].author;

    console.log(currentQuote + " \n" + currentAuthor);

    let quoteContainer = document.getElementById("quote-container");

    quoteContainer.classList.add("disappear");
    void quoteContainer.offsetWidth;
    quoteContainer.classList.remove("disappear");
    void quoteContainer.offsetWidth;
    quoteContainer.classList.remove("appear");
    
    document.getElementById("text").innerHTML = currentQuote;
    document.getElementById("author").innerHTML = "- " + currentAuthor;

    void quoteContainer.offsetWidth;
    quoteContainer.classList.add("appear");

    return {
        quote: currentQuote,
        author: currentAuthor
    };
};

document.addEventListener("DOMContentLoaded", pickARandomQuote);

let button = document.getElementById("new-quote");

if (button) {
    button.addEventListener("click", pickARandomQuote);
}

屏幕上的动画似乎独立于代码发生,因此“消失”动画没有足够的时间来播放。我尝试了“setTimeout”,但它没有帮助。

【问题讨论】:

  • 你能给我看看你的 HTML 示例吗?
  • @pond27,是的

标签: javascript css-animations


【解决方案1】:

您需要等到disappear 动画结束后才能执行appear。 其中一种方法是setTimeout 函数。

例子:

let pickARandomQuote = function() {
    index = Math.floor(Math.random() * quotes.length);
    currentQuote = quotes[index].quote;
    currentAuthor = quotes[index].author;
    let quoteContainer = document.getElementById("quote-container");

    quoteContainer.classList.remove("appear");
    quoteContainer.classList.add("disappear");
    setTimeout(function () {
        document.getElementById("text").innerHTML = currentQuote;
        document.getElementById("author").innerHTML = "- " + currentAuthor;
        quoteContainer.classList.remove("disappear");
        quoteContainer.classList.add("appear");
    }, this.duration)
};

document.addEventListener("DOMContentLoaded", { handleEvent: pickARandomQuote, duration: 0 });

let button = document.getElementById("new-quote");

if (button) {
    button.addEventListener("click", { handleEvent: pickARandomQuote, duration: 1200 });
}

但是,如果您可以使用jQuery,以下问答可能对您有用。

Jquery replacewith fade/animate

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多