Javascript 匹配元素高度jQuery/HTML
我的HTML文档中有以下结构:Javascript 匹配元素高度jQuery/HTML,javascript,jquery,html,Javascript,Jquery,Html,我的HTML文档中有以下结构: <div class="content"> <section class="column"></section> <aside class="column"></aside> </div> 尝试使用$('.column').css('height',maxHeight+'px') 顺便说一句,您可以将$('div.content').children('.column')替换为$('div.
<div class="content">
<section class="column"></section>
<aside class="column"></aside>
</div>
尝试使用$('.column').css('height',maxHeight+'px')代码>
顺便说一句,您可以将$('div.content').children('.column')
替换为$('div.content>.column')
最大限度地利用一组属性的好方法是使用.map()
:
您的问题中的函数似乎没有问题,因为使用此标记和代码时,两列的高度相同(取自您的Pastebin示例):
函数统一权重()
{
var maxHeight=0;
$('div.content').children('.column').each(function(){
var height=$(this.outerHeight();
如果(高度>最大高度){maxHeight=height;}
});
$('.column').css('height',maxHeight);
}
.内容{
背景颜色:黄色;
}
节.列{
宽度:300px;
浮动:左;
}
旁栏{
宽度:300px;
浮动:左;
显示:内联;
}
jldkjfls
jldkjfls
统一权重();
您是否测试了该匿名函数是否调用了两次,以及子函数是否正确?您是否查看了分配的高度值?maxHeight
增加了吗?我一定是做错了什么,因为这也不起作用-你能在这个测试文档中看到这可能是什么吗:@Stuart:你根本没有调用那个函数,而且,根据我的控制台,max
不是一个函数。@Marcel不,它不是--我以为它是一个本地JS数组方法。现在编辑…太棒了。多谢各位
function unifyHeights()
{
var maxHeight = 0;
$('div.content').children('.column').each(function(){
var height = $(this).outerHeight();
if ( height > maxHeight ) { maxHeight = height; }
});
$('.column').css('height', maxHeight);
}
$(document).ready(function() {
var heights = $('div.content').children('.column').map(function(idx, el) {
return $(this).outerHeight();
}).get();
$('.column').height(Math.max(heights));
});
<!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>