[英]how to get (display:none)element height using pure JavaScript?
我正在尝试获取 (display: none) 元素的高度,但它返回 0。但是当我使用 jquery 时,它使用此代码返回一个有效值。
/* My Code */ const elm = document.querySelector('.elm'); console.log(elm.clientHeight); //return 0 /* IN jQuery */ console.log($(elm).height()); //return 300
.elm{ height: 300px; width: 300px; background-color: #007bff; display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <div class="elm"></div>
我需要它使用 javascript。 我们都非常清楚,jQuery 在纯 javaScript 中所做的一切皆有可能。 提前谢谢。
[注意]我是 JavaScript 新手!
带有display: none
的元素永远不会有高度或宽度。 这是确定其尺寸的(非 jquery)方法。 它将元素临时绝对定位在视口之外,然后移除display: none
。 现在可以查询元素的尺寸。 之后,定位等反向完成,并返回找到的高度。
const hiddenEl = document.querySelector("#someEl"); console.log(`display none: ${hiddenEl.clientHeight}`); console.log(`height determined by method: ${ determineHeightOfAHiddenDivElement(hiddenEl)}`); function determineHeightOfAHiddenDivElement(elem) { elem.style.position = "absolute"; elem.style.top = "-5000px"; elem.style.display = "initial"; const height = elem.clientHeight; elem.style.display = ""; elem.style.top = ""; elem.style.position = ""; return height; }
.as-console-wrapper { top: 0; max-height: 100% !important; } #someEl { display: none; height: 300px; }
<div id="someEl">You don't see me</div>
我查看了 jQuery 源代码。 忽略处理框模型、不同浏览器等的代码,jQuery 执行以下操作:
const elm = document.querySelector('.elm'); const styles = window.getComputedStyle(elm); console.log(parseFloat(styles.height));
.elm{ height: 300px; width: 300px; background-color: #007bff; display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <div class="elm"></div>
一种选择是使用window.getComputedStyle(element)
。
const elm = document.querySelector('.elm'); const computedHeight = window.getComputedStyle(elm).height console.log('Computed height', computedHeight); console.log('Parsed', parseInt(computedHeight.replace('px', '')))
.elm{ height: 300px; width: 300px; background-color: #007bff; display: none; }
<div class="elm"></div>
另一个可能更丑陋的方法是克隆元素,给它一个display: block
,将它附加到文档并去掉它的高度,然后立即销毁克隆。
const elm = document.querySelector('.elm'); const clone = elm.cloneNode(); clone.style.display = 'block'; document.body.appendChild(clone); console.log(clone.clientHeight); document.body.removeChild(clone);
.elm{ height: 300px; width: 300px; background-color: #007bff; display: none; }
<div class="elm"></div>
你也可以暂时给元素本身display: block
,然后恢复之前的样式。
理想的解决方案可能取决于用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.