translateX 值的答案(感谢 Albert Portnoy):
var style = window.getComputedStyle(div);
var xVal = parseFloat(style.transform.split(" ")[4].replace(",", ''));
如何获取在 javascript 中使用@keyframes 设置动画的元素的当前转换值?
我使用的 css 值(translateX)在动画或完成时似乎没有变化
<style>
@keyframes anim {
from {
transform: translateX(0px)
}
to {
transform: translateX(400px)
}
}
div {
width: 50px;
height: 50px;
background: black;
animation: anim 5s forwards linear;
}
</style>
<div></div>
<script>
var div = document.getElementsByTagName('div')[0];
function loop() {
setTimeout(function () {
console.log(div.style);
loop()
}, 100)
}
loop()
</script>
最佳答案
您可以使用(尚未标准)功能 CSSMatrix .
关于 Calculating element vertex data from CSS transforms 的另一个有用解释
这是一个运行示例,请注意我使用了 requestanimationFrame而不是使用 setTimeout
的回调循环来在每一帧上运行代码。
var el = document.getElementById('root');
let count = 0;
function loop() {
requestAnimationFrame(() => {
var style = window.getComputedStyle(el);
var matrix = new WebKitCSSMatrix(style.webkitTransform);
console.log('translateX: ', matrix.m41);
if(count > 100){
// just to stop the infinite loop...
return;
}
count++;
loop();
})
}
loop()
@keyframes anim {
from {
transform: translateX(0px)
}
to {
transform: translateX(400px)
}
}
#root {
width: 50px;
height: 50px;
background: black;
animation: anim 5s forwards linear;
}
<div id="root"/>
关于javascript - 如何使用 javascript 获取@keyframes 当前转换值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56304966/