用JavaScript触发CSS动画

Trigger CSS animation with JavaScript?

本文关键字:动画 CSS 触发 JavaScript      更新时间:2023-09-26

我在这里使用了CSS:

@keyframes themesappear{
    0% {
        opacity: 0;
    } 100% {
        opacity: 1;
    }
}
@-webkit-keyframes themesappear{
    0% {
        opacity: 0;
    } 100% {
        opacity: 1;
    }
}

和这里的Javascript:

var theme = function() {
    document.getElementById('themes').style.animation = "themesMappear 2s forwards;";
    document.getElementById('themes').style.WebkitAnimation = "themesappear 2s forwards;";
};

试图使id为"themes"的div淡入并显示…

问题是onclick不工作,也不透明度改变,我怎么能解决这个问题?你可以在这里看到网站

如何使用onlclick: <h1 id = "WM" onclick = "theme()">Change Theme</h1>

一些事情

  1. 你似乎有一个错字(themesMappear而不是themesappear)
  2. 规则的末尾有一个分号,这使得它无效,因此没有添加。应该是"themesMappear 2s forwards",而不是"themesMappear 2s forwards;"
  3. 你真的应该用这些规则创建一个类,然后通过JS切换这些样式的类