这似乎应该是重复的 - 我发现了很多类似的问题 - 但没有一个答案对我有效。如果我错过了一个,请指出我,我会删除这个。
我有一个绝对定位的div包含几个子div。我希望容器扩展到最宽的子项的宽度,并希望所有其他子项扩展到相同的宽度。容器应具有最小宽度和最大高度;如果孩子太多,就应该滚动。
所以这类似于组合下拉列表的行为,尽管这在不同的上下文中使用。
我提出的解决方案适用于Chrome,Firefox和IE8,但不适用于IE7(标准模式),其中儿童不会扩展到容器的宽度。我尝试了一些改变,其中一些改变了孩子们,但都导致了其他问题。这样做的正确方法是什么?
我创建了以下示例来说明问题:
<html>
<head>
<style>
.container {
display: block;
position: absolute;
top: 50px;
left: 50px;
min-width: 100px;
max-height: 100px;
border: 1px solid #999;
overflow-x: hidden;
overflow-y: auto;
}
.entry {
display: block;
width: auto;
height: 20px;
padding: 3px 20px 3px 5px;
white-space: nowrap;
background: #eee;
}
</style>
</head>
<body>
<div class='container'>
<div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRSTUVW</div>
<div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRSTUVWXYZ</div>
<div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRST</div>
<div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQ</div>
<div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRST</div>
<div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRSTUVW</div>
</div>
</body>
答案 0 :(得分:2)
在IE7中,父div需要width:100%
或width:auto
的已定义宽度才能在子元素上正常工作。不幸的是,在父级上定义宽度会适得其反,因为您希望父级大小相对于最大的子级是动态的,而不是静态的。
现在,这个浏览器怪癖可能是无害的,你可以忽略它并留下它,但是如果你希望你的网站在IE7中仍然看起来很好,你总是可以选择使用JavaScript来设置父宽度等于最大的子元素。
以下是我使用的JavaScript:
$(function() {
/* function finds largest width of the .entry child of .container
and assigns that width to the parent .container.
This is for IE7 bug that requires a defined parent width in order for
width:auto to work on the children elements
*/
var elemWidth = 0;
var maxWidth = 0;
$('.container')
.find('.entry')
.each(function() {
// iterate through .entry and assign largest width to var elemWidth
if ( $(this).width() > elemWidth ) {
elemWidth = $(this).width();
}
});
maxWidth = elemWidth + 30; // extra 30px spacing to compensate for y-overflow
$('.container').width(maxWidth);
});
这是一个有效的jsfiddle示例:http://jsfiddle.net/qG8Qf/1/
答案 1 :(得分:0)
这应该有用......
$(function() {
var maxWidth = 0;
$('.container')
.find('div')
.each(function() { maxWidth = Math.max($(this).width(), maxWidth) })
.each(function() { $(this).width(maxWidth) })
.width(maxWidth);
});
编辑:毕竟在IE7中似乎不起作用。也许有人有修复?