conditional formatting of html table cells

前端 未结 6 1345
鱼传尺愫
鱼传尺愫 2021-02-04 12:49

Are there any out of the box solutions to have conditional formatting of HTML tables?

With conditional formatting I am more interested in having different colors as cell

6条回答
  •  Happy的楠姐
    2021-02-04 13:19

    My first take on this, given the following table structure:

    Name Score
    Allan, Paul 28
    Bartlett, James 33
    Callow, Simon 25
    Dennis, Mark 19
    Ennals, Simon 10
    Finnegan, Seamus 21

    css:

    table {
        width: 20em;
    }
    
    #score {
        width: 50%;
    }
    
    #name {
        width: 50%;
    }
    
    th {
        border-bottom: 2px solid #000;
        padding: 0.5em 0 0.1em 0;
        font-size: 1.2em;
    }
    
    td {
        border-bottom: 2px solid #ccc;
        padding: 0.5em 0 0.1em 0;
    }
    
    th:nth-child(even),
    td:nth-child(even) {
        text-align: center;
    }
    
    .vGood {
        background-color: #0f0;
    }
    
    .good {
        background-color: #0c0;
    }
    
    .avg {
        background-color: #060;
    }
    
    .poor {
        background-color: #c00;
    }
    
    .vPoor {
        background-color: #f00;
    }
    

    and jQuery:

    $('tbody tr td:not(":first")').each(
    
    function() {
        var vGood = 30,
            good = 25,
            avg = 20,
            poor = 15,
            vPoor = 10,
            score = $(this).text();
    
        if (score >= vGood) {
            $(this).addClass('vGood');
        }
        else if (score < vGood && score >= good) {
            $(this).addClass('good');
        }
        else if (score = avg) {
            $(this).addClass('avg');
        }
        else if (score < avg&& score >= poor) {
            $(this).addClass('poor');
        }
        else if (score < poor) {
            $(this).addClass('vPoor');
        }
        });
    

    JS Fiddle demo.

    This is, of course, a brute-force approach. It'll work, but it's not the most optimised/efficient approach.

提交回复
热议问题