我正在尝试从 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 获取值,就好像我是手动设置它们一样(而不是通过变换动画)。

如果这是不可能的,有没有办法模拟“圆形”旋转并在不使用变换的情况下返回右侧/顶部值?

IE:
https://66.media.tumblr.com/fb22b61bcbca3785a515e86c2276451b/tumblr_inline_pmimnjEvbK1v6q8wn_1280.gif?fbclid=IwAR2zjgE0hfB8emWOg0f6TOcQb8DWGbEvu9IQOr92fMq4HmMKjiAQRQzLmI0

最佳答案

使用 getBoundingClientRect() :

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/

10-09 15:30
查看更多