我试图从一个被 CSS 动画旋转的元素中获取 Top 和 Right 值,为此我使用了以下代码:
HTML:
<div id="ball1"> </div>
CSS:
@keyframes spin {
0% {transform: rotate(0deg);}
100% {transform: rotate(360deg);}
}
#ball1 {
transform-origin: center right;
animation: spin 2.5s linear 0s infinite forwards;
position: relative;
background-color: #7883f7;
width: 10;
height: 10;
border-radius: 10px;
}
Javascript:
console.log(window.getComputedStyle(document.getElementById("ball1"), null).top);
console.log(window.getComputedStyle(document.getElementById("ball1"), null).right);
但是它返回 0px 的值,我想从 Right 和 Top 获取值,就像我手动设置它们一样(而不是通过变换动画)。
如果这不可能,是否有一种方法可以模拟“圆形”旋转并在不使用变换的情况下返回右/顶部值?
最佳答案
const ball = document.getElementById("ball");
setInterval(() => {
const rect = ball.getBoundingClientRect();
console.log(rect.top, rect.right);
}, 300);
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
#ball {
transform-origin: center right;
animation: spin 2.5s linear 0s infinite forwards;
position: relative;
background-color: #7883f7;
width: 10px;
height: 10px;
border-radius: 10px;
}
<div id="ball"></div>
关于javascript - 从 CSS 动画元素获取顶部/右侧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54623843/