Welcome to OGeek Q&A 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...