简体   繁体   中英

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

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 color.

My table cell looks like this:

<td id="s0" onclick="selectCell(event)">0</td>

My selectCell function looks like this:

function selectCell(e){
  alert(e.target.backgroundColor);  //this gives me 'undefined'
  alert(e.target.bgcolor);          //this gives me 'undefined'
  alert(e.target.bgColor);          //nothing shows up. i don't believe this is a valid property
  //once i know i am properly grabbing the color i will do stuff with it here.
}

My CSS looks like this:

#s0 {
  border: 1px solid;
  background-color: yellow;
}

Any help would be greatly appreciated!!

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:

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

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