我有这段简短的代码,允许折叠表格的各个部分(它们就像可折叠的标题)。这很简洁,但我试图在加载页面时实现相反的情况——加载时默认折叠,但单击时可展开。我该如何去做呢?
我现在的代码如下所示,还具有仅在单击该部分中的单词时折叠的部分,而不是在单击该部分本身(单词之外)时折叠的部分。这是因为我使用标签来使可折叠。有没有办法使整行可展开/可折叠?
table {
width: 100%;
}
table,
tr,
th,
td {
border: 1px solid black;
border-collapse: collapse;
font-family: Arial;
}
[data-toggle="toggle"] {
display: none;
}
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tbody class="labels">
<tr>
<td colspan="2">
<label for="section">Click me!</label>
<input type="checkbox" id="section" data-toggle="toggle">
</td>
</tr>
</tbody>
<tbody class="hide">
<tr>
<td>Jack</td>
<td>100</td>
</tr>
<tr>
<td>Jill</td>
<td>300</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('[data-toggle="toggle"]').change(function() {
$(this).parents().next('.hide').toggle();
});
});
</script>
最佳答案
I'm trying to make for the inverse to happen upon loading the page -- to be collapsed by default on load, but expandable when clicked. How would I go about doing this?
只需在切换函数上方的 jquery 中添加一行,然后调用 .hide
类选择器并使用 .hide();
然后,当您单击触发切换功能。
also features sections that only collapse when the words in the section are clicked, not when the section itself (outside of the words) are clicked. This is because I used labels to make the collapsible. Is there a way to make the entire row expandable/collapsible?
是的...让您的标签在 CSS 文件中显示为 block ...
label {
display: block;
}
$(document).ready(function() {
$('.hide').hide();
$('[data-toggle="toggle"]').change(function() {
$(this).parents().next('.hide').toggle();
});
});
table {
width: 100%;
}
table,
tr,
th,
td {
border: 1px solid black;
border-collapse: collapse;
font-family: Arial;
}
[data-toggle="toggle"] {
display: none;
}
label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tbody class="labels">
<tr>
<td colspan="2">
<label for="section">Click me!</label>
<input type="checkbox" id="section" data-toggle="toggle">
</td>
</tr>
</tbody>
<tbody class="hide">
<tr>
<td>Jack</td>
<td>100</td>
</tr>
<tr>
<td>Jill</td>
<td>300</td>
</tr>
</tbody>
</table>
关于javascript - 如何使用 jQuery/JavaScript 默认隐藏可展开的表格单元格,并在标签外部可单击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63218480/