我想在用户单击动画后使用javascript
动态添加动画来播放动画。例如,想象connect 4 game,目的是从棋盘顶部到应放置磁珠的位置播放动画。问题在于样式已成功添加到文档中,但无法正常工作!
这是我所实施的:
function changeColor(i, j){
var div = document.querySelector(`.cell-${i}-${j}`);
div.style.backgroundColor = currentTurn;
var style = document.querySelector('style');
var keyframe = `\
@keyframes animation-${i}-${j} {\
0% {\
top: 0%;\
}\
100% {\
top: 20%;\
}\
}\
\
`
div.style.animationName = `animation-${i}-${j}`;
div.style.animationDuration = '2s';
style.innerHTML += keyframe;
}
currentTurn的值为“ red” | “蓝色”。
答案 0 :(得分:0)
请参见下文。
function changeColor(i, j) {
var div = document.querySelector(`.cell-${i}-${j}`);
div.style.backgroundColor = "blue";
var style = document.getElementsByTagName('style')[2];
var keyframe = `\
@keyframes animation-${i}-${j} {\
0% {\
top: 0%;\
}\
100% {\
top: 20%;\
}\
}\
\
`;
style.innerHTML += keyframe;
div.style.animationDuration = '2s';
div.style.animationName = `animation-${i}-${j}`;
}
changeColor(1, 1);
<style>
.cell-1-1 {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
}
</style>
<div class="cell-1-1"></div>