2010-11-11 107 views
2

我有以下构建我的HTML文档中:匹配的元素高度的jQuery/HTML

<div class="content"> 
<section class="column"></section> 
<aside class="column"></aside> 
</div> 

我想匹配部分的高度和一边的最高两者的高度。我有以下的脚本,但它不工作,任何想法:

function unifyHeights() 
    {  
     var maxHeight = 0;  
     $('div.content').children('.column').each(function(){  
     var height = $(this).outerHeight();  
     if (height > maxHeight) { maxHeight = height; }  
    });  
    $('.column').css('height', maxHeight); 
    } 
+0

你测试,如果匿名函数被调用了两次,用正确的孩子吗?你看过“高度”的值是否被赋值? 'maxHeight'增加了吗? – 2010-11-11 22:48:08

回答

0

看起来没有什么错在你的问题评价职能,因为两列使用该标记和代码(从引擎收录例如拍摄)时,得到同样的高度:

<!doctype HTML> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script> 
<script> 
function unifyHeights() 
{  
    var maxHeight = 0;  
    $('div.content').children('.column').each(function(){  
     var height = $(this).outerHeight();  
     if (height > maxHeight) { maxHeight = height; }  
    });  
    $('.column').css('height', maxHeight); 
} 
</script> 
<style> 
.content { 
background-color: yellow; 
} 
section.column { 
    width: 300px; 
    float: left; 
} 
aside.column { 
    width: 300px; 
    floaT: left; 
    display: inline; 
} 
</style> 
</head> 
<body> 
<div class="content"> 
    <section style="background-color: pink;" class="column">jldkjfls<br/><br/></section> 
    <aside style="background-color: green;" class="column">jldkjfls<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/></section> 
<script> 
    unifyHeights(); 
</script> 
</body> 
</html> 
+0

太棒了。非常感谢你 – 2010-11-11 23:33:56

1

使用$('.column').css('height', maxHeight + 'px');

BTW试试,你可以用$('div.content > .column')

0

一个很好的方式取代$('div.content').children('.column')以获得最大的一组的房产使用.map()

$(document).ready(function() {  
    var heights = $('div.content').children('.column').map(function(idx, el) { 
     return $(this).outerHeight(); 
    }).get(); 

    $('.column').height(Math.max(heights)); 
}); 
+0

我必须做一些根本性的错误,因为这也不行 - 你能否在这个测试文档中看到这可能是什么:http://pastebin.com/JqfThuQ8 – 2010-11-11 23:04:08

+0

@Stuart:你根本就没有调用这个函数另外,根据我的控制台和http://api.jquery.com,“max”不是一个函数。 – 2010-11-11 23:19:08

+0

@Marcel不,它不是 - 我认为这是一个原生的JS数组方法。现在编辑... – lonesomeday 2010-11-11 23:26:29

相关问题