Установка равных высот для div с помощью jQuery
Я хочу установить равную высоту для div с jQuery.
У всех разделов может быть разное количество контента и разная высота по умолчанию. Вот пример моего макета 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>
Я устанавливаю высоту с помощью следующей функции jQuery:
$(document).ready(function(){
var highestBox = 0;
$('.container .column').each(function(){
if($(this).height() > highestBox){
highestBox = $(this).height();
}
});
$('.container .column').height(highestBox);
});
Это работает отлично, но не в моем случае, потому что я хочу, чтобы все "столбцы" были равны только внутри одного "контейнера". Это означает, что в первом контейнере все поля должны быть выше первого, но во втором они должны быть равны второму столбцу.
Итак, вопрос в том, как мне изменить мой jQuery, чтобы достичь этого?
Спасибо!
Ответы
Ответ 1
Отвечайте на свой конкретный вопрос
Ваш код проверял все столбцы в любом контейнере, что вам нужно сделать:
- Прохождение через каждый контейнер
- Получить высоту каждого столбца в этом контейнере
- Найти самый высокий
- Примените эту высоту к каждому столбцу в этом контейнере, прежде чем переходить к следующему.
Примечание. Попробуйте указать пример jsfiddle вашей проблемы, это позволяет нам чтобы легче помочь вам и понять проблему, вы можете увидеть и это ускоряет ответы.
Быстрый (грубый) пример
$(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>
Ответ 2
$(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);
});
});
Ответ 3
Вам нужно следующее:
$('.container').each(function(){
var $columns = $('.column',this);
var maxHeight = Math.max.apply(Math, $columns.map(function(){
return $(this).height();
}).get());
$columns.height(maxHeight);
});
Объяснение
-
Следующий фрагмент создает массив высот:
$columns.map(function(){
return $(this).height();
}).get()
-
Math.max.apply( Math, array )
находит максимальное количество элементов массива
-
$columns.height(maxHeight);
устанавливает высоту всех столбцов на максимальную высоту.
Живая демонстрация
Ответ 4
Важное улучшение! (Я добавил $(this).height('auto'), перед измерением высоты - мы должны reset его авто. Тогда мы можем использовать эту функцию при изменении размера)
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);
});
}
Ответ 5
Это моя версия блоков настроек в одной и той же области... Например, у вас есть divthat, содержащий divs с именем "col"
$('.col').parent().each(function() {
var height = 0,
column = $(this).find('.col');
column.each(function() {
if ($(this).height() > height) height = $(this).height();
});
column.height(height);
});
Ответ 6
Вы также можете написать эту функцию, которая помогает создать код один раз, просто добавив имя класса или идентификатор в конце
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"));
Ответ 7
<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>
Ответ 8
Вам нужны образы, загруженные, если в контейнере есть изображения внутри.
Это также работает для реагирования.
$(document).ready(function () {
equalHeight('.column');
});
$(window).resize(function(){equalHeight('.column');});
function equalHeight(columnClass){
$('.eq-height-wrap').imagesLoaded(function(){
$('.eq-height-wrap').each(function(){
var maxHeight = Math.max.apply(null, $(this).find(columnClass).map(function ()
{
return $(this).innerHeight();
}).get());
$(columnClass,this).height(maxHeight);
});
});
}
Ответ 9
Итак, ниже сценария jquery, чтобы установить равную высоту столбцу, который Math.max вычислит высоту двух делителей и принимает наибольшую высоту, либо левую, либо правую.
$(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
Live Demo
Ответ 10
Вы можете связаться с каждым отдельным контейнером, используя .parent()
API.
Как
var highestBox = 0;
$('.container .column').each(function(){
if($(this).parent().height() > highestBox){
highestBox = $(this).height();
}
});
Ответ 11
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 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.
Ответ 12
Для этой цели есть плагин jQuery: https://github.com/dubbs/equal-height
Если вы хотите сделать все столбцы одинаковыми, используйте:
$('.columns').equalHeight();
Если вы хотите сгруппировать их по их верхней позиции, например. внутри каждого контейнера:
$('.columns').equalHeight({ groupByTop: true });
Ответ 13
function setEqualHeight(columns) {
var tallestColumn = 0;
columns.each(function(){
var currentHeight = $(this).height();
if(currentHeight > tallestColumn){
tallestColumn = currentHeight;
}
});
columns.height(tallestColumn);
}
=> setEqualHeight($('.column'));
Ответ 14
// Select and loop the container element of the elements you want to equalise
$('.equal').each(function(){
// Cache the highest
var highestBox = 0;
// Select and loop the elements you want to equalise
$('.col-lg-4', 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
$('.col-lg-4',this).height(highestBox);
});
});
Ответ 15
<div class('a')>
<div class('.cols-to-eq')></div>
<div class('.cols-to-eq')></div>
<div class('.cols-to-eq')></div>
<div class('.cols-to-eq')></div>
</div>
<div class('b')>
<div class('.cols-to-eq')></div>
<div class('.cols-to-eq')></div>
<div class('.cols-to-eq')></div>
<div class('.cols-to-eq')></div>
</div>
var a = ['.a','.b'];
a.forEach(function(value) {
var column = 0;
$(value).find('.cols-to-eq').each(function(){
if($(this).height() > column){
column = $(this).height();
}
});
$(value).find('.cols-to-
eq').attr('style','height:'+column+'px');
});
Ответ 16
Я хотел бы прочитать этот пост, прежде чем я (с помощью графа) создал этот пост
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);
});
}