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

时间:2020-04-26 09:08:35

标签: 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');
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的内容

1 个答案:

答案 0 :(得分:1)

首先,在所有地方都删除这些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>