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



我知道这是一种很混乱的方法,但也许可以做到。。。什么语法适合通过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将是style.animationDuration:的有效值

var cue = document.createElement('div');
cue.setAttribute('id', 'cue');
cue.setAttribute(
'style',
'opacity:' + '0;'
);
cue.textContent = "hello";
var cueAnimation = document.createElement('style');
cueAnimation.type = 'text/css';
var rules = document.createTextNode('@keyframes pop {'+
'0% { opacity:0; }'+
'50% { opacity:1; }'+
'100% { opacity:0; }'+
'}');
cueAnimation.appendChild(rules);
cue.appendChild(cueAnimation);
appContainer.appendChild(cue);
cue.style.animationName = 'pop';
cue.style.animationDuration = '2s';
<div id="appContainer"></div>

pop 2s看起来更像缩写animation属性:

var cue = document.createElement('div');
cue.setAttribute('id', 'cue');
cue.setAttribute(
'style',
'opacity:' + '0;'
);
cue.textContent = "hello";
var cueAnimation = document.createElement('style');
cueAnimation.type = 'text/css';
var rules = document.createTextNode('@keyframes pop {'+
'0% { opacity:0; }'+
'50% { opacity:1; }'+
'100% { opacity:0; }'+
'}');
cueAnimation.appendChild(rules);
cue.appendChild(cueAnimation);
appContainer.appendChild(cue);
cue.style.animation = 'pop 2s';
<div id="appContainer"></div>

但我不得不指出,如果您正在编写动态样式表,那么设置元素的内联样式就没有什么意义了;也可以在样式表中设置这些样式:

var cue = document.createElement('div');
cue.setAttribute('id', 'cue');
cue.textContent = "hello";
var cueAnimation = document.createElement('style');
cueAnimation.type = 'text/css';
var rules = document.createTextNode( '' +
'#cue {' +
'  opacity: 0;'+
'  animation: pop 2s infinite;'+
'}' +
'@keyframes pop {'+
'  0% { opacity:0; }'+
'  50% { opacity:1; }'+
'  100% { opacity:0; }'+
'}');
cueAnimation.appendChild(rules);
cue.appendChild(cueAnimation);
appContainer.appendChild(cue);
<div id="appContainer"></div>

最新更新