gpt4 book ai didi

javascript - HTML/CSS : what's a better option for layout of a tree of nested elements than nested tables?

转载 作者:太空狗 更新时间:2023-10-29 13:32:50 24 4
gpt4 key购买 nike

好的,我有一组用于选择条件的复选框。为了便于讨论,我们假设数据如下所示:

[] Vehicles
[] Unpowered
[] Bicycle
[] Skateboard
[] Powered
[] Two-wheeled
[] Motorcycle
[] Scooter
[] Four-wheeled
etc

[] 代表复选框。

忽略这个例子明显做作的本质,想法是这样的:

  • 首先,只有 Vehicle 复选框可见;
  • 如果用户点击 Vehicle 复选框,则选择进入下一级别(有动力、无动力);
  • 如果用户选择 Powered,它会打开下一个级别(双轮、四轮);
  • 如果用户随后取消选中 Powered,该级别就会消失。

现在,通过 onclick 在 block 和 none 之间切换 display CSS 属性,设置起来相对容易。

目前在页面上的结构如下:

<table>
<tr>
<td><input type="checkbox" onclick="toggle('__Vehicles');"></td>
<td>Vehicles
<table id="__Vehicles">
<tr>
<td><input type="checkbox"></td>
<td>Unpowered
etc

我应该在有人问之前指出:复选框放在表格单元格中的原因是为了控制格式。这使得有效缩进变得容易,因为下一个表格单元格中的所有内容都会对齐。

一切正常,但表格嵌套变得很深。我一直认为必须有比这更好的方法。它必须能够轻松地动态构建,并且对“树”的格式具有良好的跨浏览器支持。

我还应该提到 jQuery 是可用的。我正在用它做其他事情。

建议?

编辑:是的,复选框样式很重要,正如一些评论所指出的那样。此外,我已经根据我得到的回复发布了一个解决方案,作为下面的答案(太大而无法在此处添加),仅供那些好奇地查看示例的人使用。

最佳答案

<ul>
<li><input type="checkbox" />Vehicles <ul>
<li><input type="checkbox" />Unpowered</li>
<li><input type="checkbox" />Bicycle</li>
<li><input type="checkbox" />Skateboard</li>
</ul></li>
<li><input type="checkbox" />Powered <ul>
<li><input type="checkbox" />Two-wheeled <ul>
<li><input type="checkbox" />Motorcycle</li>
<li><input type="checkbox" />Scooter</li>
</ul></li>
<li><input type="checkbox" />Four-wheeled</li>
</ul></li>
</ul>

编辑:一些 css 和 js 来显示和隐藏嵌套元素(无复选框)

li.opened ul {
display: block;
}

li.closed ul {
display: none;
}

和 js...

$(document).ready(function() {

$('li input:checkbox').click(function () {
$(this).parent().toggleClass('opened');
$(this).parent().toggleClass('closed');
});

$('li').addClass('closed');
});

再次编辑,因为 Sparr 想要一些更好的样式(假设复选框的样式为“checkbox”

li input.checkbox { /* input:checkbox is not 100% compatible */
width: 6px;
margin: 0 2px;
/* This makes 10px be the total "width" ofh the checkbox */
}

ul {
margin: 0 0 0 10px; /* Or whatever your total checkbox width is */
padding: 0;
}

li {
padding: 0;
}

关于javascript - HTML/CSS : what's a better option for layout of a tree of nested elements than nested tables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/485573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com