2013-05-01 137 views
0

我很难均衡两个浮动div的高度。我试图完成的是显示 相同的高度在两个divs并排,因为内容的长度将会改变。现在我的浏览器似乎只是忽略了Jquery代码。与jquery自动高度divs相同的高度

以下是我有:

<style> 
#column_first { 
    width: 300px 
    float: left; 
    margin: 15px; 
    padding: 25px; 
    background-color:#fff; 
} 
#column_second { 
    width:300px; 
    float: left; 
    margin: 15px; 
    padding: 25px; 
    background-color:#fff; 
    height: auto; 
} 
</style> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
<script> 
var maxHeight = 0; 

$("#column_first").each(function(){ 
    if ($(this).height() > maxHeight) { maxHeight = $(this).height(); } 
}); 

$("#column_second").height(maxHeight); 
</script> 
</head> 
<body> 
<div id="column_first"><p>Some Text</p></div> 
<div id="column_second"><p>Some Text</p></div> 

回答

3

如果你想你的平衡的div的高度,用这个:

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

jsFiddle example

您指定了特定div通过他们的ID,所以这些变化将不适用于所有的div。就我个人而言,我会给他们一个共同的班级,而不是目标。

注意,也请务必将您的jQuery的文件准备好电话:

$(document).ready(function() { 
    // Your code here 
}); 
+1

它作品!! :D谢谢。 – irm 2013-05-01 20:40:03

0

可以得到同等高度列纯CSS:

http://cssdeck.com/labs/dxtwufys

body { /* styles for the container element */ 
    display: table; 
    border-spacing: 15px; 
} 

#column_first, #column_second { 
    display: table-cell; 
} 

#column_first { 
    width: 300px; 
    /*margin: 15px; ignored*/ 
    padding: 25px; 
    background-color:#fff; 
} 
#column_second { 
    width:300px; 
    /*margin: 15px; ignored*/ 
    padding: 25px; 
    background-color:#fff; 
}