我无法尝试触发 CSS 动画。
我的 CSS:
h3[id="balance-desktop"]{
color: black;
-webkit-animation-name: gogreen;
-webkit-animation-duration: 2s;
animation-name: gogreen;
animation-duration: 2s
}
/* Safari 4.0 - 8.0 */
@-webkit-keyframes gogreen {
from {color: black;}
to {color: limegreen;}
from{color: limegreen;}
to{color: black;}
}
/* Standard syntax */
@keyframes gogreen {
from {color: black;}
to {color: limegreen;}
from{color: limegreen;}
to{color: black;}
}
这是一个改变 h3[id=balance-desktop]
元素颜色的基本动画。
动画在页面加载时起作用。当我调用我的 java 脚本函数时,我试图让它工作,但我也做不到。
尝试 #1:
function showGreenAmiamtion(){
var test = document.getElementById("balance-desktop");
test.style.webkitAnimationName = 'gogreen';
test.style.webkitAnimationDuration = '4s';
}
尝试#2:
function showGreenAmiamtion(){
document.getElementById("balance-desktop").style.webkitAnimationName = "";
setTimeout(function ()
{
document.getElementById("balance-desktop").style.webkitAnimationName = "gogreen";
}, 0);
}
我尝试了 How to activate a CSS3 (webkit) animation using javascript? 中的所有答案, 运气不好。
我的代码有问题吗?
最佳答案
您的尝试 2 有效 - 只是稍微清理了您的代码以删除 webkit 前缀(已经过时了几年)。我将 animationName 内联设置为 'none'
,然后将其删除,以便该元素恢复使用其原始 CSS 动画名称。
另外,在关键帧动画中有多个 from
和 to
是行不通的,所以我将其格式化为使用百分比。
var btn = document.getElementById("button");
var text = document.getElementById("balance-desktop");
function turngreen() {
text.style.animationName = 'none';
setTimeout(function() {
text.style.animationName = null;
}, 0);
}
btn.addEventListener('click', turngreen);
#balance-desktop {
color: black;
animation: gogreen 2s;
}
@keyframes gogreen {
0%, 100% { color: black; }
50% { color: limegreen; }
}
<h3 id="balance-desktop">Heading</h3>
<button id="button">Turn Green</button>
关于javascript - 如何触发CSS动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45495551/