[英]Make DOM elements equal by height
我编写JavaScript / TypeScript函数:
function setElementsHeightsEqual(el1: HTMLElement, el2: HTMLElement) {
...
}
当您要动态地将某些按钮(el2)附加到某些输入(el1)时,这是典型情况。
我想使el2的高度等于el1,但是我做不到。 有两个问题:
所有可能返回高度的呼叫对我来说都是无奈的:
el1.offsetWidth; // will return 0 if document is not rendered yet el1.style.height; // will return "" if it is set inside external CSS el1.style.paddingTop; // the same el1.style.paddingBottom; // the same
换句话说,是否有可能计算某些指定元素的高度?
这些任务在JS + HTML DOM中是不可能的吗?
offsetHeight是一种安全的方法。 如果未加载该元素,请将函数调用移至window.onload。
这里有一个工作示例:
function setMaxHeight(...elements) { console.log(elements); // Get max height var height = 0; for(let element of elements) { console.log(element.offsetHeight); if(element.offsetHeight > height) height = element.offsetHeight; } // Change all elements height to max. for(let element of elements) { element.style.height = height + 'px'; } } window.onload = function() { var object1 = document.querySelector('.object1'); var object2 = document.querySelector('.object2'); var object3 = document.querySelector('.object3'); setMaxHeight(object1, object2, object3); };
.object1 { border: 1px solid #000; display: block; float: left; height: 50px; width: 20%; } .object2 { border: 1px solid #0cc; display: block; float: left; height: 120px; width: 30%; } .object3 { border: 1px solid #afc; display: block; float: left; height: 20px; width: 10%; }
<div id="container"> <div class="object1">Text</div> <div class="object2">Text2</div> <div class="object3">Text3</div> </div>
比较有无Javascript部分的运行情况。
我希望这有帮助。
这是我为想要的元素设置相等高度的方法。 为您要使其高度相同的元素命名一个类名。
<div class="sameElementHeight">
<img src="/path/to/Image" class="sameImageHeight">
<p>YOUR TEXT</p>
</div>
<div class="sameElementHeight">
<img src="/path/to/Image" class="sameImageHeight">
<p>YOUR TEXT</p>
</div>
<div class="sameElementHeight">
<img src="/path/to/Image" class="sameImageHeight">
<p>YOUR TEXT</p>
</div>
首先,创建如下函数:
equalheight = function(container){
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array(),
$el,
topPosition = 0;
jQuery(container).each(function() {
$el = jQuery(this);
jQuery($el).height('auto')
topPostion = $el.position().top;
if (currentRowStart != topPostion) {
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
rowDivs.length = 0; // empty the array
currentRowStart = topPostion;
currentTallest = $el.height();
rowDivs.push($el);
} else {
rowDivs.push($el);
currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
}
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
});
}
然后在关闭body标签之前调用它:
<script>
equalheight(".sameElementHeight");
equalheight(".sameImageHeight");
</script>
</body>
当您向文档中添加新元素时,也可以调用此函数。 它将计算元素的高度并为其设置相同的高度,并且对图像也执行相同的操作。
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.