我想计算一个元素的高度(例如 div
),以 px 为单位,当它没有默认值(= initial
或 auto
)时使用 JavaScript 。
请注意,我的元素现在有另一个高度值(例如 40 像素),但我想了解如果将其设置为 initial
其高度(以像素为单位)是多少。或auto
.
换句话说:
myElement.style.height = '40px'; // for example
// ...
console.log(myElement.clientHeight); // This logs "40". This is not the value I want.
myElement.style.height = 'initial';
console.log(myElement.clientHeight); // This logs the value I want. But I don't want to execute above statement AT ALL!
最佳答案
如果我理解正确的话,如果元素没有定义精确的高度样式值,您希望能够获得元素将具有的高度?
答案很简单:你不能。浏览器必须渲染 DOM 才能访问链接到它的值,例如 clientHeight。
但是,您可以使用一些hacky方法,例如将高度设置为auto
,读取它,然后将其设置回40px,或者使用隐藏元素(可见性:隐藏,而不是显示:无,因为您需要渲染它),但请注意这有点脏并且难以维护。
关于javascript - 当元素没有默认值时计算其默认高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40854945/