通过JavaScript动态创建CSS关键帧动画

通过JavaScript动态创建CSS关键帧动画,javascript,css,css-animations,Javascript,Css,Css Animations,我知道这是一个混乱的方式试图完成这一点,但也许它可以做到。。。 什么语法适合通过JavaScript动态分配关键帧CSS动画 var cue = document.createElement('div'); cue.setAttribute('id', 'cue'); cue.setAttribute( 'style', 'opacity:' + '0;' ); var cueAnimation = document.createElement('style'); cueAni

我知道这是一个混乱的方式试图完成这一点,但也许它可以做到。。。 什么语法适合通过JavaScript动态分配关键帧CSS动画

var cue = document.createElement('div');
cue.setAttribute('id', 'cue');
cue.setAttribute(
    'style',
    'opacity:' + '0;'
);

var cueAnimation = document.createElement('style');
cueAnimation.type = 'text/css';
var rules = document.createTextNode('@-moz-keyframes pop {'+
    '0% { opacity:0; }'+
    '50% { opacity:1; }'+
    '100% { opacity:0; }'+
    '}');
cueAnimation.appendChild(rules);
cue.appendChild(cueAnimation);

appContainer.appendChild(cue);

...

cue.style.mozAnimationName = 'pop 2s'; //not sure how to trigger this...

注意,在这个演示中,我只针对Firefox,为了简单起见,“cue”div的内容也被省略了

首先,去掉所有的
moz
前缀,Firefox支持多年来不固定的动画,每个浏览器也是如此。(此外,它是
style.MozXXX

然后,
style.animationName
应该是动画的名称(是),并且您的动画被称为“
pop
”,而不是“
pop 2s

2s
将是
样式的有效值。animationDuration

var-cue=document.createElement('div');
setAttribute('id','cue');
cue.setAttribute(
“风格”,
'不透明度:'+'0;'
);
cue.textContent=“你好”;
var cueAnimation=document.createElement('style');
cueAnimation.type='text/css';
var rules=document.createTextNode(“@keyframes pop{”+
'0%{不透明度:0;}'+
'50%{不透明度:1;}'+
'100%{不透明度:0;}'+
'}');
cueAnimation.appendChild(规则);
追加子对象(提示动画);
appContainer.appendChild(提示);
cue.style.animationName='pop';
cue.style.animationDuration='2s'

尝试将
cueAnimation
添加到
cue
元素,而不是
head
元素,如图所示。非常好!非常感谢:)