Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - Rotate a table 90 degrees

I have a table that looks something like this:

<table><tbody>
    <tr><td>a</td><td>1</td></tr>
    <tr><td>b</td><td>2</td></tr>
    <tr><td>c</td><td>3</td></tr>
    <tr><td>d</td><td>4</td></tr>
    <tr><td>e</td><td>5</td></tr>
    <tr><td>f</td><td>6</td></tr>
    <tr><td>g</td><td>7</td></tr>
</tbody></table>

I need it to get to something like this:

<table><tbody>
    <tr>
        <td>a</td><td>b</td><td>c</td><td>d</td>
        <td>e</td><td>f</td><td>g</td>
    </tr>
    <tr>
        <td>1</td><td>2</td><td>3</td><td>4</td>
        <td>5</td><td>6</td><td>7</td>
    </tr>
</tbody></table>

example

I'm thinking something like this should work, but I'm kinda lost, how would I go about this: Here's what I started

I'm open to Javascript, jQuery or even CSS for this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This will swap the rows and columns of any size tbody, as long as rows all have the same number of cells.

<!doctype html>
<html lang= "en">
<head>
<meta charset= "utf-8">
<title> Small Test Page</title>
</head>
<body>
<script>
function tableSwap(){
    var t= document.getElementsByTagName('tbody')[0],
    r= t.getElementsByTagName('tr'),
    cols= r.length, rows= r[0].getElementsByTagName('td').length,
    cell, next, tem, i= 0, tbod= document.createElement('tbody');

    while(i<rows){
        cell= 0;
        tem= document.createElement('tr');
        while(cell<cols){
            next= r[cell++].getElementsByTagName('td')[0];
            tem.appendChild(next);
        }
        tbod.appendChild(tem);
        ++i;
    }
    t.parentNode.replaceChild(tbod, t);
}
</script>
<h1> Small Test Page</h1>
<p> <button type= "button" id= "tableSwapBtn" onclick= "tableSwap()"> 
Swap rows and columns</button> </p>
<table style="width:300px;border:1px" rules="all">
<tbody>
<tr> <td> a</td> <td> 1</td> </tr>
<tr> <td> b</td> <td> 2</td> </tr>
<tr> <td> c</td> <td> 3</td> </tr>
<tr> <td> d</td> <td> 4</td> </tr>
<tr> <td> e</td> <td> 5</td> </tr>
<tr> <td> f</td> <td> 6</td> </tr>
<tr> <td> g</td> <td> 7</td> </tr>
</tbody>
</table>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...