Using javascript, how do I get the background color of a table cell when I click on it?

前端 未结 2 750
独厮守ぢ
独厮守ぢ 2021-01-13 10:18

I want to have an alert pop up that shows me the background of a table cell whenever i click on it. I just can\'t seem to find or figure out how to grab the background colo

相关标签:
2条回答
  • 2021-01-13 10:58

    You can do it easily by Jquery css() function

    jQuery(document).ready(function(){
        $(this).click(function () {
              var color = $(this).css("background-color");
              alert(color);
         });
     });
    

    For more detail have a look at this example

    0 讨论(0)
  • 2021-01-13 11:14

    The styles of a node are in the styles property, for example:

    e.target.style.backgroundColor;
    

    However this works only for those styles declared with the in-line style attribute. If CSS is assigned (as it should be) using a stylesheet, you'll need to use:

    window.getComputedStyle(e.target, null).backgroundColor;
    

    Internet Explorer, unfortunately, doesn't implement the getComputedStyle() option, instead offering currentStyle (mind, they don't support e.target either, I think, at least in versions prior to 8?). I don't have Internet Explorer with which to test, but the docs suggest that it should be used:

    var e = window.event ? window.event : e,
        elementNode = e.target !== null ? e.target : e.srcElement;
    elementNode.currentStyle.backgroundColor;
    

    References:

    • currentStyle.
    • Element.style.
    • window.getComputedStyle().
    0 讨论(0)
提交回复
热议问题