简体   繁体   中英

Change CSS of another div when hover on Table cell

I have seen similar post on stack exchange where you can change css of another div when hovered over one div. However in my case it is not working as I am using this with a table cell.

Here, is the HTML code:

 body { padding: 5%; } .tbdata { background-color: royalblue; color: white; cursor: pointer; } .tooltip { color: white; opacity: 0; transition: opacity 1s; background-color: red; min-width: 50px; min-height: 100px; } .tbdata:hover ~ .tooltip { opacity: 1; } .tbdata:hover ~ .tooltip:after { content: attr(data-); } 
 <table> <tr> <td class="tbdata" data-="This is the tooltip text for col1">This is table data1</td> <td class="tbdata" data-="This is the tooltip text for col2">This is table data2</td> </tr> </table> <div class="tooltip"> </div> 

I want to make the .tooltip div visible when hovered over the .tbdata and also change the content using attr() from the table cell.

Please suggest.

You cannot change the content property dynamically on hover, however, you can use some "trickery" to hide a span and show another.

This example below shows how you can do just that. This, as far as I know, is the best solution for a non-JS implementation of dynamically changing a div content on hover

 .button{ background:lightblue; width:200px; } .tooltip{ background:red; width:200px; } .tooltip .before { display: block; } .tooltip .after { display: none; } .button:hover .tooltip{ background:green; } /* Hide the `.before` and show the `.after` */ .button:hover .tooltip .before{ display:none; } .button:hover .tooltip .after { display:block; } 
 <div class="button"> Hover over me! <div class="tooltip"><span class="before">Turn nothing</span><span class="after">Into something</span></div> </div> 

To hide/show the content, you would also apply display property changes to the .tooltip . I've left both div visible for this demonstration, however, to show the changing content.

I used Jquery for this solution.

  $('document').ready(function(){



  $('.tbdata').hover(
  function(){

        $(".tooltip").css("visibility","visible");
        $(".tooltip").attr("attrname","attrvalue"); //attribute
  },
  function(){

        $(".tooltip").css("visibility","hidden");
        $(".tooltip").attr("attrname","attrvalue"); //attribute

  }

  );

});

Here is example: Fiddle

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