我在另一个包含表格的 div2 旁边有一个 div1。该表是动态创建的,有时会比 div1 长。如何使用javascript根据div2中表格的元素数量动态更改div1的高度?
答案 0 :(得分:0)
window.onresize = (() => {
setTimeout(() => {
$('#div1').css(
'height',
document.querySelector('#div2').offsetHeight + 1
)
}, 10);
});
$('#div1').css(
'height',
document.querySelector('#div2').offsetHeight
)
#div1 {
float: left;
width: 50%;
background-color: red;
}
#div2 {
float: right;
width: calc(50% - 16px);
padding: 8px;
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id = 'div1'>hello world</div>
<div id = 'div2'>
<!--copied from
https://www.w3schools.com/html/tryit.asp?filename=tryhtml_table_intro-->
<table border = '2'>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
</div>
</body>