使用 jQuery 为 div 设置相等的高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11688250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting equal heights for div's with jQuery
提问by Mitya Ustinov
I want to set equal height for divs with jQuery. All the divs may have different amount of content and different default height. Here is a sample of my html layout:
我想用 jQuery 为 div 设置相等的高度。所有的 div 可能有不同数量的内容和不同的默认高度。这是我的 html 布局示例:
<div class="container">
<div class="column">This is<br />the highest<br />column</div>
<div class="column">One line</div>
<div class="column">Two<br />lines</div>
</div>
<div class="container">
<div class="column">One line</div>
<div class="column">Two<br>lines</div>
<div class="column">One line</div>
</div>
I'm setting the height with the next jQuery function:
我正在使用下一个 jQuery 函数设置高度:
$(document).ready(function(){
var highestBox = 0;
$('.container .column').each(function(){
if($(this).height() > highestBox){
highestBox = $(this).height();
}
});
$('.container .column').height(highestBox);
});
This works fine but not in my case because I want all the 'columns' equal only inside one 'container'. This means that in the first container all the boxes must be as high as the first div, but in the second one they must be equal to second column.
这工作正常,但在我的情况下不是,因为我希望所有“列”仅在一个“容器”内相等。这意味着在第一个容器中所有的框必须和第一个 div 一样高,但在第二个容器中它们必须等于第二列。
So question is -- how should I modify my jQuery to reach this?
所以问题是——我应该如何修改我的 jQuery 来达到这个目的?
Thank you!
谢谢!
回答by Lee
Answer to your specific question
回答您的具体问题
Your code was checking all columns within any container, what you need to do is:
您的代码正在检查任何容器中的所有列,您需要做的是:
- Loop through each container
- Get the heights of each column within that container
- Find the highest one
- Apply that height to every column in that container before moving on to the next one.
- 循环遍历每个容器
- 获取该容器内每一列的高度
- 找到最高的
- 在移动到下一列之前,将该高度应用于该容器中的每一列。
Note: Try to provide an example jsfiddle of your issue, it enables us to more easily help you and understand the issue, you get to see the working solution straight away and it encourages quicker responses.
注意:尝试提供您的问题的示例 jsfiddle,它使我们能够更轻松地帮助您并了解问题,您可以立即看到有效的解决方案,并鼓励更快的响应。
Quick (Rough) Example
快速(粗略)示例
$(document).ready(function(){
// Select and loop the container element of the elements you want to equalise
$('.container').each(function(){
// Cache the highest
var highestBox = 0;
// Select and loop the elements you want to equalise
$('.column', this).each(function(){
// If this box is higher than the cached highest then store it
if($(this).height() > highestBox) {
highestBox = $(this).height();
}
});
// Set the height of all those children to whichever was highest
$('.column',this).height(highestBox);
});
});
.container { border 1px solid red; }
.column { border: 1px solid blue; float:left; width: 30%; text-align:center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="column">This is<br />the highest<br />column</div>
<div class="column">One line</div>
<div class="column">Two<br />lines</div>
</div>
<div class="container">
<div class="column">One line</div>
<div class="column">Two<br>lines</div>
<div class="column">One line</div>
</div>
Library!
Here's a library i found that looks promising if you want some more clever equalisation controls
图书馆!
这是我发现的一个库,如果您想要一些更聪明的均衡控制,它看起来很有希望
Addressing @Mem's question
解决@Mem 的问题
Question: Will
$(document).ready()
work if you have images that need to load which in turn modify the heights of the containers?
问题:
$(document).ready()
如果您有需要加载的图像进而修改容器的高度,这会起作用吗?
Equalising heights after image load
图像加载后均衡高度
If you are loading images, you will find that this solution doesn't always work. This is because document.ready
is fired at the earliest possible time, which means it does not wait for external resources to be loaded in (such as images).
如果您正在加载图像,您会发现此解决方案并不总是有效。这是因为document.ready
在尽可能早的时间被触发,这意味着它不会等待加载外部资源(例如图像)。
When your images finally load, they may distort the heights of their containers after the equalisation script has run, causing it too appear not too work.
当您的图像最终加载时,它们可能会在均衡脚本运行后扭曲其容器的高度,导致它看起来不太工作。
Solving equalising heights with images
用图像解决均衡高度
- Bind to image loading events
- 绑定到图片加载事件
This is the best solution (at the time of writing) and involves binding to the img.load
event. All you have to do is get a count of how many img's there are $('img').length
and then for each load
, -1
from that count until you hit zero, then fire the equaliser.
这是最好的解决方案(在撰写本文时)并且涉及到img.load
事件的绑定。您所要做的就是计算有多少 img $('img').length
,然后对每个img进行计数load
,-1
从该计数直到您达到零,然后触发均衡器。
The caveat here is load
may not fire in all browsers if the image is in the cache. Look around google/github, there should be a solution script out there. At the time of writing i found waitForImages from Alexander Dickson(untested, this is not an endorsement).
load
如果图像在缓存中,这里的警告可能不会在所有浏览器中触发。环顾google/github,那里应该有一个解决方案脚本。在撰写本文时,我发现了 Alexander Dickson 的 waitForImages(未经测试,这不是认可)。
- Another more reliable solution is the
window.load
event. This should generally always work. However, if you check the docsout, you'll notice this event fires after ALL external resources are loaded. This means if your images are loaded but there's some javascript waiting to download it won't fire until that completes.
- 另一个更可靠的解决方案是
window.load
事件。这通常应该始终有效。但是,如果您查看文档,您会注意到在加载所有外部资源后会触发此事件。这意味着如果您的图像已加载但有一些 javascript 等待下载,则在完成之前不会触发。
If you load the majority of your externals asyncronously and are clever with minimising, compressing and spreading the load you probably wont have any issues with this method, however a suddenly slow CDN (happens all the time) could cause issues.
如果您异步加载大部分外部组件并且巧妙地最小化、压缩和分散负载,您可能不会对这种方法有任何问题,但是突然变慢的 CDN(一直发生)可能会导致问题。
In both cases, you could take a dumb approach and apply fallback timers. Have the equalise script run automatically after a set few seconds just in case the event doesn't fire or something is slow out of your control. It's not fool proof, but in reality you'll satisfy 99% of your visitors with this fallback if you tune the timer correctly.
在这两种情况下,您都可以采用愚蠢的方法并应用回退计时器。让均衡脚本在设定的几秒钟后自动运行,以防事件没有触发或某些事情超出您的控制范围。这不是万无一失的,但实际上,如果您正确调整计时器,您将通过这种回退来满足 99% 的访问者。
Years later this is still getting upvotes, with flexbox widely supported these days you may want to consider just plain CSS for this, unless there's a specific reason you are using JS for it
多年后,这仍然得到了赞成,如今 flexbox 得到广泛支持,您可能只想为此考虑使用纯 CSS,除非您出于特定原因使用 JS
.container {
display: flex;
border: 2px dashed red;
margin: 10px 0;
}
.container > .column {
padding: 10px;
}
.container.fill-width {
justify-content: stretch;
}
.container.fill-width>.column {
flex-grow: 1
}
.container>.column:nth-child(1) {
background: yellow;
}
.container>.column:nth-child(2) {
background: blue;
}
.container>.column:nth-child(3) {
background: green;
}
<div class="container">
<div class="column">Some<br>text</div>
<div class="column">Some<br>more<br>text<br>here</div>
<div class="column">One line</div>
</div>
<div class="container">
<div class="column">Some<br>more<br>even<br>longer<br>text<br>here</div>
<div class="column">Some<br>text</div>
<div class="column">One line</div>
</div>
<div class="container fill-width">
<div class="column">Some<br>more<br>text<br>here</div>
<div class="column">Some<br>text</div>
<div class="column">One line</div>
</div>
回答by Snow Blind
$(document).ready(function(){
$('.container').each(function(){
var highestBox = 0;
$(this).find('.column').each(function(){
if($(this).height() > highestBox){
highestBox = $(this).height();
}
})
$(this).find('.column').height(highestBox);
});
});
回答by Engineer
You need this:
你需要这个:
$('.container').each(function(){
var $columns = $('.column',this);
var maxHeight = Math.max.apply(Math, $columns.map(function(){
return $(this).height();
}).get());
$columns.height(maxHeight);
});
Explanation
解释
The following snippet constructs an array of the heights:
$columns.map(function(){ return $(this).height(); }).get()
Math.max.apply( Math, array )
finds the maximum of array items$columns.height(maxHeight);
sets all columns' height to maximum height.
以下代码段构造了一个高度数组:
$columns.map(function(){ return $(this).height(); }).get()
Math.max.apply( Math, array )
查找数组项的最大值$columns.height(maxHeight);
将所有列的高度设置为最大高度。
回答by squarepixell
Important improvement! (I added $(this).height('auto'); before measuring height - we should reset it to auto. Then we can use this function on resize)
重要改进!(我添加了 $(this).height('auto'); 在测量高度之前 - 我们应该将其重置为自动。然后我们可以在调整大小时使用此功能)
function equalheight () {
$('.cont_for_height').each(function(){
var highestBox = 0;
$('.column_height', this).each(function(){
var htmlString = $( this ).html()
;
$(this).height('auto');
if($(this).height() > highestBox)
highestBox = $(this).height();
});
$('.column_height',this).height(highestBox);
});
}
回答by Scribilicious
This is my version of setting blocks in the same hight... For example you have a divthat contains divs with the name "col"
这是我在同一高度设置块的版本...例如,您有一个包含名为“col”的 div 的 div
$('.col').parent().each(function() {
var height = 0,
column = $(this).find('.col');
column.each(function() {
if ($(this).height() > height) height = $(this).height();
});
column.height(height);
});
回答by Faizal
So, below the jquery script to set the equal height to column which Math.max will calculate the two divs height and takes the highest height either it may be left or right.
因此,在 jquery 脚本下方将相等的高度设置为 Math.max 将计算两个 div 高度并采用最高高度的列,它可能位于左侧或右侧。
$(document).ready(function() {
var Equalheights = Math.max($(“#left”).height(), $(“#right”).height());
$(“#left”). Equalheights(d);
$(“#right”). Equalheights(d);
});
Highest height will be assigned to both left and right divs
回答by Tristanisginger
I wish i'd read this post before I (with help from Earl) created this one
我希望在我(在厄尔的帮助下)创建这篇文章之前阅读这篇文章
setMaxHeightForTitles($column, $title) {
var maxHeight = 0;
$column.find($title)
.each(function(index, title){
var height = $(title).height();
if (height > maxHeight) maxHeight = height;
})
.each(function(index, title){
$(title).height(maxHeight);
});
}
回答by Chetan bane
You can write the function this way also Which helps to build your code one time just to add class name or ID at the end
您也可以通过这种方式编写函数,这有助于一次性构建您的代码,只需在最后添加类名或 ID
function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = jQuery(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
equalHeight(jQuery("Add your class"));
回答by krishanan
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array(),
$el,
topPosition = 0;
$('.blocks').each(function() {
$el = $(this);
topPostion = $el.position().top;
if (currentRowStart != topPostion) {
// we just came to a new row. Set all the heights on the completed row
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
// set the variables for the new row
rowDivs.length = 0; // empty the array
currentRowStart = topPostion;
currentTallest = $el.height();
rowDivs.push($el);
} else {
// another div on the current row. Add it to the list and check if it's taller
rowDivs.push($el);
currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
}
// do the last row
for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
});?
$('.blocks') would be changed to use whatever CSS selector you need to equalize.
回答by Minu Alex
<script>
function equalHeight(group) {
tallest = 0;
group.each(function() {
thisHeight = $(this).height();
if(thisHeight > tallest) {
tallest = thisHeight;
}
});
group.height(tallest);
}
$(document).ready(function() {
equalHeight($(".column"));
});
</script>