我没有找到确切的示例,因此,如果有的话,请指向我的链接。我在上一个问题中也犯了一个错误,因此我给出了正确的答案,但我仍然需要帮助!
我想使HTML中的表响应如下-CSS可以吗?
<table>
<thead>
<tr>
<td>HEADER Data 1</td>
<td>HEADER Data 2</td>
<td>HEADER Data 3</td>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
<td>Row 1 Data 3</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
<td>Row 2 Data 3</td>
</tr>
<tr>
<td>Row 3 Data 1</td>
<td>Row 3 Data 2</td>
<td>Row 3 Data 3</td>
</tr>
</tbody>
</table>
在小屏幕上,我希望表响应,以便将数据放置如下:
由此:
HEADER Data 1 HEADER Data 2 HEADER Data 3
Row 1 Data 1 Row 1 Data 2 Row 1 Data 3
Row 2 Data 1 Row 2 Data 2 Row 2 Data 3
Row 3 Data 1 Row 3 Data 2 Row 3 Data 3
对此:
HEADER Data 1
Row 1 Data 1
Row 2 Data 1
Row 3 Data 1
HEADER Data 2
Row 1 Data 2
Row 2 Data 2
Row 3 Data 2
HEADER Data 3
Row 1 Data 3
Row 2 Data 3
Row 3 Data 3
最佳答案
使用CSS无法将表拆分成其列的块。因此,需要Javascript。像这样:
<body>
<h1>Test</h1>
<table id="responsiveTable">
<thead>
<tr>
<td>HEADER Data 1</td>
<td>HEADER Data 2</td>
<td>HEADER Data 3</td>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
<td>Row 1 Data 3</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
<td>Row 2 Data 3</td>
</tr>
<tr>
<td>Row 3 Data 1</td>
<td>Row 3 Data 2</td>
<td>Row 3 Data 3</td>
</tr>
</tbody>
</table>
<hr>
<script>
var table = document.getElementById("responsiveTable");
var changeTable = function(e) {
if (document.body.clientWidth < 400) {
if (document.getElementById("responsiveTable")) {
var tr = null;
var td = null;
var cols = [];
for ( i=0; i<table.getElementsByTagName("tr").length; i++ ) {
tr = table.getElementsByTagName("tr")[i];
for ( j=0; j<tr.getElementsByTagName("td").length; j++) {
td = tr.getElementsByTagName("td")[j];
if(cols[j]==null) cols[j]=[];
cols[j][i] = td;
}
}
var divWrapper = document.createElement("div");
divWrapper.id = "divWrapper";
var divCol = null;
var divData = null;
for ( j=0; j<cols.length; j++ ) {
divCol = document.createElement("div");
for ( i=0; i<cols[j].length; i++ ) {
divData = document.createElement("div");
divData.innerHTML = cols[j][i].innerHTML;
divCol.appendChild(divData);
}
divWrapper.appendChild(divCol);
}
document.body.replaceChild(divWrapper, table);
}
} else if (document.getElementById("divWrapper")) {
document.body.replaceChild(table, document.getElementById("divWrapper"));
}
}
window.addEventListener("load", changeTable, true);
window.addEventListener("resize", changeTable, true);
</script>
</body>
小提琴:http://jsfiddle.net/ch3sqx8j/
问候
阿克塞尔