我在两个不同的父 div 下有三列。我需要为这三列设置相同的高度。
我的问题是:
- 3列在不同父div下,不能使用display:table和table-cell方法
- 在 col-2 中有一个标签列表,当你点击不同的标签时,它会改变 block 的高度
我试过用JS设置等高,没成功:
a) JS 得到错误的 col-2 高度,因为它计算所有部分的总高度,但不是事件部分。
b) JS设置了一个固定的高度值。当我缩小窗口大小时或单击 col-2 中的不同选项卡时,列高不会相应调整。 col里面的内容可能会溢出。
HTML代码:
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div>
<div class="left-wraper">
<header>Head1</header>
<div class="col-1">
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
</div>
<div class="col-2">
<header>Topic 2</header>
<ul class="list-inline">
<li><a href="#menu1">Menu 1</a></li>
<li><a href="#menu2">Menu 2</a></li>
<li><a href="#menu3">Menu 3</a></li>
</ul>
<section id="menu1" role="tabpanel">
<p>
This is menu1<br> This is menu1<br> This is menu1<br>
</p>
</section>
</div>
</div>
<div class="right-wraper">
<span>Head2</span>
<div class="col-3">
<header>Topic 2</header>
<p>
sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text<br> sample text
</p>
</div>
</div>
</div>
CSS 代码:
.left-wraper {
width: 65%;
float: left;
padding: 8px;
background-color: #b3ffcb;
}
.right-wraper {
width: 28%;
float: left;
padding: 8px;
margin-left: 8px;
background-color: #ffccef;
}
.col-1 {
width: 30%;
float: left;
background-color: #e6ccfe;
}
.col-2 {
width: 70%;
float: left;
background-color: #ffeecd;
}
.col-3 {
width: 100%;
float: left;
background-color: #b3d9ef;
}
在上面的演示中需要一种方法来为 block 紫色、黄色和蓝色动态设置相等的高度。不仅在加载时,而且在单击不同的选项卡或调整屏幕大小时也是如此。
最佳答案
我建议添加一个实用程序类来分离您在 css 和 js 中所做的事情。 考虑到这一点,我已经更新了你的 fiddle 。下面的代码将在加载和单击时为您工作。我需要在更多上下文中查看它以调整大小,因为它保持 fiddle 的高度或调整大小。
var $body = $('body');
findHeight('.findHeight');
function findHeight(el){
var heightArr = [];
$(el).each(function(){
heightArr.push($(this).outerHeight());
});
var tallest = Math.max.apply(null, heightArr);
$(el).css('height', tallest);
heightArr = [];
}
$body.on('click', 'div[class^="col-"]', function(){
findHeight('.findHeight');
});
您会注意到我已经将 findHeight 类添加到相关元素中。您可以将其更改为您想要的任何内容。只需确保也在 js 中执行此操作即可。
关于javascript - 如何为不同父div下的列动态设置等高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37738093/