2011-12-21 105 views
1

尝试使用jQuery匹配div高度,并且似乎我只能将其与最小高度相匹配,但我希望它匹配最高的列。从我能告诉代码应该找到最高的列?所以我很困惑,这里是我使用使用jQuery匹配div高度

function matchColHeights(col1, col2) { 
    var col1Height = $(col1).height(); 
    var col2Height = $(col2).height(); 
    if (col1Height < col2Height) { 
     $(col1).height(col2Height); 
    } else { 
     $(col2).height(col1Height); 
    } 
} 

$(document).ready(function() { 
    matchColHeights('#leftPanel', '#rightPanel'); 
}); 

想在这里做:http://www.tigerstudiodesign.com/blog/

+0

链接到你的网站是一个好主意,但_which bits_你想匹配的高度? – Bojangles 2011-12-21 20:08:51

+0

leftPanel和rightPanel,就像代码状态一样。 – Lukasz 2011-12-21 20:10:04

+0

'leftPanel'和'rightPanel'可能是_anything_。此外,当他们不在同一高度时,您不告诉我们要寻找什么。对我而言,页面设计在FF中可以正常工作。你能提供正确/不正确的截图或图表或其他? – Bojangles 2011-12-21 20:12:39

回答

2

这应能设置多个列maxheight。只需指定选择器,就像你想用jQuery选择所有元素一样。

function matchColHeights(selector){ 
    var maxHeight=0; 
    $(selector).each(function(){ 
     var height = $(this).height(); 
     if (height > maxHeight){ 
      maxHeight = height; 
     } 
    }); 
    $(selector).height(maxHeight); 
}; 

$(document).ready(function() { 
    matchColHeights('#leftPanel, #rightPanel, #middlePanel'); 
}); 
+0

这似乎现在工作至少附加一个高度,但我需要它来抓住最大高度,这抓住了最低高度。 – Lukasz 2011-12-21 20:25:30

2

一行替代

$(".column").height(Math.max($(col1).height(), $(col2).height())); 

看看这个小提琴:http://jsfiddle.net/c4urself/dESx6/

这似乎为我工作得很好?

的JavaScript

function matchColHeights(col1, col2) { 
    var col1Height = $(col1).height(); 
    console.log(col1Height); 
    var col2Height = $(col2).height(); 
    console.log(col2Height); 
    if (col1Height < col2Height) { 
     $(col1).height(col2Height); 
    } else { 
     $(col2).height(col1Height); 
    } 
} 

$(document).ready(function() { 
    matchColHeights('#leftPanel', '#rightPanel'); 
}); 

CSS

.column { 
    width: 48%; 
    float: left; 
    border: 1px solid red; 
} 

HTML

<div class="column" id="leftPanel">Lorem ipsum...</div> 
<div class="column" id="rightPanel"></div> 
+0

有没有高度设置....?它怎么可能工作? – Lukasz 2011-12-21 20:24:07

+0

div的自动增长取决于其内容 – c4urself 2011-12-21 20:25:13

+0

我知道,这是问题所在。 heh:/ – Lukasz 2011-12-21 20:34:09

0

当我在Chrome中,#leftPa加载你的网站nel的高度为1155px,#rightPanel的高度为1037px。然后,通过matchColHeights方法将#rightPanel的高度设置为1155px。

但是,如果我允许加载页面,那么使用Chrome Developer Tools控制台删除在#rightPanel上设置明确高度的style属性,其高度变为1473px。所以,你的代码在代码运行时正确地将两列中较短的那一列设置为较高的高度。但后续的页面格式化会使其他列更高。