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
165 views
in Technique[技术] by (71.8m points)

javascript - How to convert columns to rows using CSS

Hi I need to convert columns to rows and rows to columns. I have both column headers and rows headers to the left. The row headers are just bold text to the left of the row to define what the row is.

I am trying to make this table mobile friendly. The table is 7 columns wide and the 7 columns do not show in a smart phone. So my idea is to use a media query to display a table where the columns and rows are switched since there will be no more than 3 rows. Can this be done?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

DEMO

Css Solution: Simply turn your td & th to display:block; & your tr to display:table-cell;

CSS:

@media screen and (max-width:767px) {
    table tr > *{
        display: block;
    }
    table tr {
        display: table-cell;
    }
}

Drawback: If your cells have too much data the layout will break Example.

jQuery Solution: We can keep track of element height to stay the same DEMO

JS:

$(function () {
    switchRowsAndCols("table", 767);
});

function switchRowsAndCols(thisTable, resolution) {
    if ($(window).width() < resolution) {
        switchRowsAndColsInnerFun(thisTable);
    }
    $(window).resize(function () {
        if ($(window).width() < resolution) {
            switchRowsAndColsInnerFun(thisTable);
        }else{
            switchRowsAndColsRemove(thisTable);
        }
    });
};

function switchRowsAndColsRemove(thisTable) {
    $("tr > *", thisTable).css({
        height: 'auto'
    });
};

function switchRowsAndColsInnerFun(thisTable) {
    var maxRow = $("tr:first-child() > *", thisTable).length;

    for (var i = maxRow; i >= 0; i--) {

        $("tr > *:nth-child(" + i + ")", thisTable).css({
            height: 'auto'
        });

        var maxHeight = 0;

        $("tr > *:nth-child(" + i + ")", thisTable).each(function () {
            var h = $(this).height();
            maxHeight = h > maxHeight ? h : maxHeight;
        });

        $("tr > *:nth-child(" + i + ")", thisTable).each(function () {
            $(this).height(maxHeight);
        });
    };
};

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

...