我有一个动态表,其中动态创建行和表。我有一个使用CSS设置的滚动条。我试图在行>时显示滚动条2使用js但它没有用。如果行大于2,我想显示滚动条请指导我实现此目的。有关更多信息,请查看下面的代码(代码有2个表仅用于测试)。任何帮助将受到高度赞赏
//i want to display scroll bar based on number of rows if row >2 then display the scroll bar
//this is how i am adding row in my table
if ($('#testbody2 >tr').length > 2){
$('#testbody2').css('overflow-y', 'visible');}

.table1 th{
border:2px solid black;
}
.table1 tbody{
display:inline-block;
max-height: 80px;
overflow-y: auto;
}
.table2 tbody{
display:block;
height: 25px;
overflow-y: hidden;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>my first table</h3>
<div>
<table class="table1">
<thead>
<tr>test1</tr>
</thead>
<tbody id="testbody">
<tr><td>test</td></tr>
<tr><td>test</td>
</tr><tr>
<td>test</td></tr>
</tbody>
</table>
</div>
<h3>my second table</h3>
<div>
<table class="table2">
<thead>
<tr>test3</tr>
</thead>
<tbody id="testbody2">
<tr><td>test</td></tr>
<tr><td>test</td></tr>
</tr><td>testing</td></tr>
<tr><td>testing</td><tr>
<td>test</td></tr>
</tbody>
</table>
</div>
&#13;
答案 0 :(得分:3)
在您的评论代码中,您缺少#来选择ID。 这应该有用。
if ($('#testbody > tr').length > 2)
$('#testbody').css('overflow-y', 'scroll');
答案 1 :(得分:1)
你需要设置父div的高度,当行溢出时,CSS工作
.table1 th{
border:2px solid black;
}
.table1 tbody{
display:inline-block;
max-height: 80px;
}
#tb{
display:block;
height: 100px;
overflow-y: auto;
}
#tb2{
display:block;
height: 100px;
overflow-y: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>my first table</h3>
<div id="tb">
<table class="table1">
<thead>
<tr>test1</tr>
</thead>
<tbody id="testbody">
<tr><td>test</td></tr>
<tr><td>test</td>
</tr><tr>
<td>test</td></tr>
</tbody>
</table>
</div>
<h3>my second table</h3>
<div id="tb2">
<table class="table2">
<thead>
<tr>test3</tr>
</thead>
<tbody id="testbody2">
<tr><td>test</td></tr>
<tr><td>test</td></tr>
</tr><td>testing</td></tr>
<tr><td>testing</td><tr>
<td>test</td></tr>
</tbody>
</table>
</div>
<!-- end snippet -->