CSS: set color for selected row in a table

前端 未结 4 670
無奈伤痛
無奈伤痛 2020-12-31 23:28

I need to add the following feature to my table:

When the user clicks on a row (selects it), the row is marked with the color #FFCF8B (the same as

4条回答
  •  抹茶落季
    2021-01-01 00:06

    In order to add a .selected class to your clicked row you need a bit of JavaScript.

    Example http://jsfiddle.net/thebabydino/KzVfy/

    I used jQuery for the example, so there is very little code:

    $("tr").click(function(){
        $(this).addClass("selected").siblings().removeClass("selected");
    });​
    

    Of course, it can be done without using any library if you don't wish to include jQuery.


    Just for variation, I did another version. This one uses no library (no jQuery, no Mootools, no YUI, no Dojo, and so on...) and selects multiple rows. Can be seen at http://jsfiddle.net/thebabydino/nY5jj/ with a variation that unselelects a selected row when clicking on it again http://jsfiddle.net/thebabydino/nY5jj/1/

    The JavaScript is:

    var trs = document.querySelectorAll("tr");
    for(var i = 0; i < trs.length; i++){
        trs[i].addEventListener("click", function(){this.className += " selected";});
    }​
    

    To unselect a selected row when clicking on it a second time :

    var trs = document.querySelectorAll("tr");
    for(var i = 0; i < trs.length; i++){
        trs[i].addEventListener("click", function(){
            var cn = this.className, thc = " selected", start_idx = cn.indexOf(thc);
            if(start_idx == -1) cn += thc;
            else cn = cn.replace(thc,"");
            this.className = cn;
        });
    }​
    

提交回复
热议问题