【发布时间】:2021-11-05 09:12:04
【问题描述】:
我是 JS 的新手,我想知道如何使用 JS 添加样式,例如...
document.getElementById("id").style.transform = "translateX(50%)";
...但不与我在 css 中写的样式重叠。
这是我的例子。 CSS:
#falling-block {
margin-top: 21px;
}
@keyframes falling {
from {
transform: translateY(0%);
margin-bottom: 0;
}
to {
transform: translateY(1250%);
margin-bottom: 0;
}
}
这是我的 JS:
const ranCol = Math.floor(Math.random()*3);
const fallingBlock = document.getElementById('falling-block');
if (ranCol==0) {
fallingBlock.style.transform = 'translateX(-28%)';
} else if (ranCol==1) {
fallingBlock.style.transform = 'translateX(0%)';
} else if (ranCol==2) {
fallingBlock.style.transform = 'translateX(28%)';
}
fallingBlock.style.animation = 'falling 4s linear infinite';
所以它改变了 JS 中的变换,但我仍然想要已经写好的变换。我可以只添加 translateY 并保留 translateX 吗?谢谢!
【问题讨论】:
-
translateX也应该是动画的吗?
标签: javascript css transform