使用jQuery使页面上的多个元素具有相同的高度

时间:2015-08-17 13:35:02

标签: javascript jquery

我有一个函数,用于在类equalheight的页面上创建所有相同高度(最高元素的高度)的元素:

equalheight = function(container){

    var currentTallest = 0,
        currentRowStart = 0,
        rowDivs = new Array(),
        $el,
        topPosition = 0;

    $(container).each(function() {
        $el = $(this);
        $($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);
        }
    });
}

$(window).load(function() {
    equalheight('.equalheight');
});

$(window).resize(function(){
    equalheight('.equalheight');
});

我遇到的问题是,让我说我有两排盒子。我希望所有的第一行都是相同的高度,所以我给它们类equalheight。好的。好。现在,我还希望第二行的框具有相同的高度,但只是第二行中的那些框。

有什么办法可以修改这段代码,让我可以设置多组元素的相等高度?例如,可能会将类设置为equalheight1equalheight2等等?

编辑:我想到的一件事是在每个元素上添加一个数据属性,并为具有相同数据属性的每个元素计算最高元素。像:

<div class="equalheight" data-equalgroup="1"> </div>

8 个答案:

答案 0 :(得分:5)

我们遍历所有元素并将它们添加到currentRow列,并更新最大高度。当我们到达其顶部与前一个元素不同的元素时,我们更新currentRow列的所有高度,然后我们将currentRow设置为新的,最后在退出循环后,我们更新最后一行列的高度。

equalheight = function (container) {
  var currentRow = { cols: [], h: 0 };
  var topPostion = -1;
  $(container).each(function () {
       var $el = $(this);
       $($el).height('auto')
       if (topPostion != $el.position().top) {
            for (var j = 0; j < currentRow.cols.length; j++) {
                currentRow.cols[j].height(currentRow.h);
            }
            topPostion = $el.position().top;
            currentRow = { cols: [], h: 0 };
        }
        currentRow.cols.push($el);
        if ($el.height() > currentRow.h) {
            currentRow.h = $el.height();
        }

  });
  for (var j = 0; j < currentRow.cols.length; j++) {
       currentRow.cols[j].height(currentRow.h);
  }
}
$(window).load(function() {
     equalheight('.equalheight');
});

$(window).resize(function(){
    equalheight('.equalheight');
});     

这是一个fiddle

答案 1 :(得分:1)

据我所知,你应该能够为每一行提供一个不同的类,并且只需在每一行上运行该函数;

$(window).load(function() {
    equalheight('.equalheight-row-1');
    equalheight('.equalheight-row-2');
});

$(window).resize(function(){
    equalheight('.equalheight-row-1');
    equalheight('.equalheight-row-2');
});

虽然仔细查看代码,但它似乎实际上正在处理它(使用currentRow的东西)。

编辑:你实际上没有拥有给每一行一个不同的类,只需这样做;

$('.equalheight-row').each(function () {
    equalheight($(this));
});

该函数应该在每一行上单独运行。

答案 2 :(得分:1)

在我看来它应该像添加到加载和调整大小函数一样简单:

$(window).load(function() {
    equalheight('.equalheight1');
    equalheight('.equalheight2');
});

$(window).resize(function(){
    equalheight('.equalheight1');
    equalheight('.equalheight2');
});

请注意班级名称。

答案 3 :(得分:1)

您可以为要分组的div添加第二个类。类似的东西:

<div class="equalheight first"></div>
<div class="equalheight first"></div>
<div class="equalheight second"></div>
<div class="equalheight second"></div>

然后在你的javascript中:

$(window).load(function() {
    equalheight('.first.equalheight');
    equalheight('.second.equalheight');
});

答案 4 :(得分:1)

如果您的目标不需要IE8或更早版本,您可以使用flexbox布局解决此问题。

HTML

<div class="rows">
    <div class="cell">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus illo quibusdam, perspiciatis vel officiis alias autem consequuntur labore mollitia omnis natus, fuga, illum id deleniti assumenda amet harum deserunt cum.</div>
    <div class="cell"><div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid provident, quaerat ducimus perspiciatis omnis sint aspernatur quibusdam saepe, quam similique eligendi nisi nesciunt atque laudantium quidem, doloribus culpa deserunt laboriosam.</div>
    <div>Aspernatur porro vitae beatae nam fuga nisi magni eaque commodi odio voluptate veritatis laboriosam animi, ullam optio quidem sequi ducimus voluptas quaerat adipisci dignissimos. Velit sequi mollitia nemo veritatis optio.</div></div>
    <div class="cell">Voluptate suscipit, laudantium. A, veniam repellat iste eligendi magnam at nisi quod suscipit laudantium tenetur porro accusamus quam quae nulla voluptatibus molestiae quisquam quos doloremque dolorum ipsam rem. Non, sunt.</div>
    <div class="cell">Tempore praesentium voluptas earum harum numquam consequatur commodi omnis, debitis fuga suscipit, quae repellat hic iure molestiae doloribus. Eveniet voluptate quam placeat fugit iusto consequatur nam eaque porro eligendi itaque.</div>
    <div class="cell">Sed deleniti ullam iusto pariatur natus, voluptatibus iste, ipsum assumenda dolor provident vel eum quisquam odit placeat in eligendi! Doloremque corporis maxime non culpa iusto rerum incidunt excepturi illum veniam.</div>
    <div class="cell">Ullam provident fuga doloremque beatae possimus, facilis veritatis quae officia ut, atque expedita qui nulla adipisci, voluptate quas ipsam dolore vel architecto sapiente tenetur tempora laborum blanditiis libero. Saepe, ad!</div>
    <div class="cell">Molestiae quam impedit sequi suscipit, rerum hic quia saepe excepturi, in assumenda inventore maxime vero. Earum aperiam dicta aut voluptas, rerum, repudiandae modi deserunt minima nostrum recusandae sequi, sunt natus!</div>
</div>

CSS

.rows {
    margin: 15px auto;
    width: 960px;
    padding: 15px;
    border: 1px solid;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-flex-wrap: wrap;
            -ms-flex-wrap: wrap;
                    flex-wrap: wrap;
}

.cell {
    min-width: 270px;
    max-width: 275px;
    -webkit-box-flex: 1;
    -webkit-flex: 1;
            -ms-flex: 1;
                    flex: 1;
    padding: 15px;
    border: 1px solid #F0F0F0;
    margin: 7.5px;
}

演示:http://codepen.io/pjetr/pen/wabJYe

答案 5 :(得分:1)

我可能会走得太远,但是如果您使用jQuery,为什么不构建这样的插件?

我将使用Chris Dobson建议的相同name属性方法

$.fn.equalHeight=function(){
    var $this=$(this);
    heights={};
    function setup(e){
        var n=$(e).attr('name');
        if(!heights[n])heights[n]=[];
        heights[n].push($(e).height());
        //console.log(heights);     
    };
    function getHighest(name){
        return Math.max.apply(null,heights[name]);
    };
    function setHeights(){
        $this.height(getHighest($this.attr('name')));
        //$this.foreach(function(){
           // $this.height(getHighest($(this).attr('name')));
       // });
    };
    $this.each(function(){
        return setup($this);//think I need a return here?
    });
    $('window').on('resize, load',function(){
       setHeights(); 
    });
    setHeights(); 
};
$(document).ready(function(){
$('.equalheight').equalHeight();

});

我还使用this question来帮助你回答;)

可能想让别人仔细检查一下。我也要去测试它。

答案 6 :(得分:1)

实现目标的有效方法之一是将任务分为两个功能。

  1. 根据一个函数中的行设置框的高度
  2. 根据另一个函数中的顶部偏移量为行提供类名(如equalheight1,equalheight2 ..)。
  3. JS:

    $(document).ready(function () {
        equalheight = function () {
            var rowIndex = 1;
            while ($('.equalheight' + rowIndex ).length) {
                var currDivs = [];
    
                $('.equalheight' + rowIndex ).each(function () {
                    currDivs.push($(this).height());
                });
    
                var maxHeight = Math.max.apply(Math, currDivs);
    
                $('.equalheight' + rowIndex).each(function () {
                    $(this).height(maxHeight);
                });
                rowIndex++;
            }
        };
    
        assignRows = function () {
            // Reassign classes based on top offset
            var allBoxes = $('.equalheight');
            allBoxes.removeClass();
            var rowIndex = 1;
            var currentRowTop = 0;
            var rowMap = {};
    
            for (var i = 0; i < allBoxes.length; i++) {
                if (rowMap[$(allBoxes[i]).position().top] === undefined)
                    rowMap[$(allBoxes[i]).position().top] = [];
                rowMap[$(allBoxes[i]).position().top].push(allBoxes[i]);
            }
    
            for (var row in rowMap) {
                for (var i = 0; i < rowMap[row].length; i++) {
                    $(rowMap[row][i]).addClass('equalheight equalheight' + rowIndex);
                }
                rowIndex++;
            }
        };
    
        assignRows();
        equalheight();
    
        $(window).resize(function () {
            assignRows();
            equalheight();
        });
    });
    

    在HTML中,所有框都具有相同的类equheight。例如:

    <div class="equalheight">Element1</div>
    <div class="equalheight">Element2</div>
    <div class="equalheight">Element3</div>
    

    JSFiddle:https://jsfiddle.net/w4j7Lwap/2/

答案 7 :(得分:0)

尝试将属性(例如名称)添加到元素中 - 单选按钮使用与name元素类似的方法来确定哪些按钮组合在一起。

您可以使用equalheight类和新类选择,例如。 equal1只选择一个组中的元素并分别处理每个组。

<div class="equalheight equal1"></div>
<div class="equalheight equal1"></div>
<div class="equalheight equal2"></div>
<div class="equalheight equal2"></div>

然后在你的JavaScript中:

var equalGroupOne = $(".equalheight.equal1")
setHeightEqual(equalGroupOne);

var equalGroupTwo = $(".equalheight.equal2")
setHeightEqual(equalGroupTwo);

function setHeightEqual(equalGroup) {
  //Your code here...
}

*我的初始答案提示name属性和jQuery attributeEquals选择器,但name属性不适合div元素。另一种方法是使用HTML5的data-*属性,并且有一个论证是正确的,但是新类似乎更合适(请参阅下面的评论以获取更多信息)。