获取HTML元素的边界框,不包括CSS转换

Getting bounding box of an HTML element excluding CSS transforms

本文关键字:不包括 CSS 转换 边界 HTML 元素 获取      更新时间:2023-09-26

我意识到这曾经是getBoundingClientRect()的默认行为,但似乎我是在罕见的位置需要这个功能!

我有一个CSS动画,使用translate在Y轴上移动一个div。但是,我想要div的最后位置…但是在动画开始之前。

假设我不知道动画参数,有什么(整洁的)方法可以做到这一点吗?

您可以直接使用getBoundingClientRect。
下面是一个例子:

var element = document.getElementById("move");
window.setInterval(function() {
  var structure = element.getBoundingClientRect();
  element.innerHTML = "left: " + Math.floor(structure.left) + "px<br/> top: " + Math.floor(structure.top) + "px";
}, 100);
body {
  background-color: #222;
  height: 450px;
}
#move {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: white;
  animation: move 5s infinite alternate;
}
@keyframes move {
  from {
    left: 0;
    top: 0;
  }
  to {
    left: calc(100% - 200px);
    top: calc(100% - 200px);
  }
}
<div id="move">HELLO!</div>