【发布时间】:2011-02-20 22:45:37
【问题描述】:
我想显示一个基本的 html 表格,其中包含用于切换显示/隐藏附加列的控件:
<table id="mytable">
<tr>
<th>Column 1</th>
<th class="col1">1a</th>
<th class="col1">1b</th>
<th>Column 2</th>
<th class="col2">2a</th>
<th class="col2">2b</th>
</tr>
<tr>
<td>100</td>
<td class="col1">40</td>
<td class="col1">60</td>
<td>200</td>
<td class="col2">110</td>
<td class="col2">90</td>
</tr>
</table>
因此,默认情况下,第 1 列和第 2 列将是唯一显示的列 - 但是当您单击第 1 列时,我希望 1a 和 1b 切换,与 2a 和 2b 的第 2 列相同。我最终可能会得到更多的列和更多的行 - 所以当我测试时,任何 javascript 循环方法都太慢而无法使用。
似乎足够快的唯一方法是像这样设置一些 css:
table.hide1 .col1 { display: none; }
table.hide2 .col2 { display: none; }
table.hide3 .col3 { display: none; }
table.show1 .col1 { display: table-cell; }
table.show2 .col2 { display: table-cell; }
table.show3 .col3 { display: table-cell; }
然后在将触发切换的表格标题单元格上设置 onClick 函数调用 - 并确定将“mytable”设置为哪个 css 类将创建我正在寻找的切换效果。有没有一种简单的方法来设置它,以便代码可以用于 n # 列?
更新
这是我想出的,效果很好 - 而且速度非常快。如果您能想出改进的方法,请告诉我。
CSS
.col1 {display: none; }
.col2 {display: none; }
.col3 {display: none; }
table.show1 .col1 { display: table-cell; }
table.show2 .col2 { display: table-cell; }
table.show3 .col3 { display: table-cell; }
Javascript
function toggleColumn(n) {
var currentClass = document.getElementById("mytable").className;
if (currentClass.indexOf("show"+n) != -1) {
document.getElementById("mytable").className = currentClass.replace("show"+n, "");
}
else {
document.getElementById("mytable").className += " " + "show"+n;
}
}
还有 html sn-p:
<table id="mytable">
<tr>
<th onclick="toggleColumn(1)">Col 1 = A + B + C</th>
<th class="col1">A</th>
<th class="col1">B</th>
<th class="col1">C</th>
<th onclick="toggleColumn(2)">Col 2 = D + E + F</th>
<th class="col2">D</th>
<th class="col2">E</th>
<th class="col2">F</th>
<th onclick="toggleColumn(3)">Col 3 = G + H + I</th>
<th class="col3">G</th>
<th class="col3">H</th>
<th class="col3">I</th>
</tr>
<tr>
<td>20</td>
<td class="col1">10</td>
<td class="col1">10</td>
<td class="col1">0</td>
<td>20</td>
<td class="col2">10</td>
<td class="col2">8</td>
<td class="col2">2</td>
<td>20</td>
<td class="col3">10</td>
<td class="col3">8</td>
<td class="col3">2</td>
</tr>
</table>
【问题讨论】:
-
好的,所以似乎没有其他方法可以做到这一点 - 但有没有办法做到这一点,所以它是一个“粘性”切换?现在,每次我显示一列时,正在显示的另一列进入隐藏状态。我想我必须添加css规则来专门处理每个排列???如果我处理 5 个显示/隐藏列,我希望不会……不会很有趣。
-
嗯 IE7 不喜欢我发布的解决方案。我可以让它与默认显示的所有列一起工作,但不能默认隐藏...
-
您可以添加多个类:
table.className= 'show1 show3'等。我怀疑 IE 的问题是,正如我所提到的,它不支持display: table-cell。我会使用像hide这样的类而不是show,所以你只需要声明table.hide1 col1 { display: none; }。
标签: javascript html css html-table