目前,Element.getBoundingClientRect()
提供元素的位置和尺寸,但它会自动考虑通过 CSS transform
属性进行的转换。如何在没有转换的情况下得到矩形?
在下面的示例中,我希望输出为 10 10 100 100
。
const rect = div.getBoundingClientRect()
document.write(`${rect.left} ${rect.top} ${rect.width} ${rect.height}`)
body {
margin: 10px;
}
div {
background: red;
width: 100px;
height: 100px;
transform: translate(1px, 1px) scale(0.5)
}
<div id="div"></div>
最佳答案
Here is already an answer, you can read more on this post: How do I retrieve an HTML element's actual width and height?
因此,您可以通过将代码更改为以下内容来获取转换“之前”的实际值
document.write(`${div.offsetLeft} ${div.offsetTop} ${div.offsetWidth} ${div.offsetHeight}`)
body {
margin: 10px;
}
div {
background: red;
width: 100px;
height: 100px;
transform: translate(1px, 1px) scale(0.5)
}
<div id="div"></div>
关于javascript - 如何在转换之前获取元素的矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435561/