[英]How to get the longest height of the div from pure javascript?
我正在嘗試通過jQuery實現什么,但是我避免使用jQuery學習JavaScript。 我正在嘗試從.map
獲取最大的數字。 到目前為止,這是我所做的。
function equalHeight(className) {
var i = Array.from(document.getElementsByClassName(className));
i.forEach(function(items) {
console.info(Math.max(items.scrollHeight));
});
}
但這什么都不記錄
console.info(items.scrollHeight);
記錄所有三個數字。
我知道我錯過了一個基本的錯誤,有人可以指出我在做什么錯嗎?
基本上,我想獲得最長的高度並將其設置為其他div
我將使用.getBoundingClientRect()
並在每次迭代中進行比較
function equalHeight(className) {
const elements = Array.from(document.getElementsByClassName(className));
let highest = 0;
elements.forEach(function(item) {
const itemH = item.getBoundingClientRect().height;
highest = itemH > highest ? itemH : highest;
});
return highest;
}
文件: https : //developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
我不是100%確切地知道您要追求的是什么,但是有幾件事:
1)從getElementsByClassName
切換到querySelectorAll
將為您提供一個內置forEach
的對象。
2)您只向Math.max
傳遞了1個值
function equalHeight(className) { var max = 0; document.querySelectorAll(className).forEach( function(el) { console.info(Math.max(el.scrollHeight, max)); if (el.scrollHeight > max) { max = el.scrollHeight; } } ); return max; } var max = equalHeight('.test'); console.info('Max div height:', max);
div { border: 1px dashed red; margin: 2px 0; }
<div class="test">one</div> <div class="test">one<br/>two</div> <div class="test">one<br/>two<br/>three</div>
UPDATE
對於您的問題“現在如何使用此值作為其余div的高度”:
function getMaxHeight(className) { var max = 0; document.querySelectorAll(className).forEach( function(el) { console.info(Math.max(el.scrollHeight, max)); if (el.scrollHeight > max) { max = el.scrollHeight; } } ); return max; } function setHeight(className, height) { document.querySelectorAll(className).forEach( function(el) { el.style.height = height+'px'; } ); } var max = getMaxHeight('.test'); console.info('Max div height:', max); setHeight('.test', max);
div { border: 1px dashed red; margin: 2px 0; }
<div class="test">one</div> <div class="test">one<br/>two</div> <div class="test">one<br/>two<br/>three</div>
但是,一旦執行此操作,所有DIV都不會再次更改高度。
您可以設置el.style.minHeight
,然后再次檢查是否更改了DIV中的任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.