简体   繁体   中英

Change color of a CSS when mouse hover an TD

I'm developing an site with a large table (18 row x 11 columns). To make it easier for who is looking that table, I made it hover an different color for the TR with that:

.responsive tr:hover {
    background-color: red;
}

But I want to make the same with the column. But if I use .responsive td:hover {background-color: blue;} , it just hovers the single TD, not the entire column. At least, every TD has the class col1 , col2 , etc.

How is it possible to change a CSS property when hovering the TD. If this is possible, I can change the background-color from class col1 when I hover the col1 TD.

Any idea?

There is no concept of column in HTML or CSS.

You must use javascript to do that.

Here's a solution using jQuery :

var clean = function(){
   $('td').removeClass('colHover');
}
$('td').hover(
    function() {
       clean();
       $('td:nth-child('+($(this).index()+1)+')').addClass('colHover');
    }, clean
);

Demonstration


Now, mainly for fun, if you want to handle colspan, you could do that :

var clean = function(){
   $('td').removeClass('colHover');
}
$('td').hover(
    function() {
       clean();
       var col = 0;
      $(this).prevAll().each(function(){col += parseInt($(this).attr('colspan')||'1')});
      $('tr').each(function(){
        var c = 0, done = false;
        $('td',this).each(function(){
          if (c>col && !done) {
            $(this).prev().addClass('colHover');
            done = true;
          }
          c += parseInt($(this).attr('colspan')||'1');
        });
        if (!done) $(this).find('td:last-child').addClass('colHover');
      });
    }, clean
);

Demonstration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM