使用javascript,当我点击它时,如何获得表格单元格的背景颜色?

Mr *_*tic 5 html javascript background-color

我希望弹出一个警告,只要我点击它就会显示表格单元格的背景.我似乎无法找到或弄清楚如何抓住背景颜色.

我的表格单元格如下所示:

<td id="s0" onclick="selectCell(event)">0</td>
Run Code Online (Sandbox Code Playgroud)

我的selectCell函数如下所示:

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.
}
Run Code Online (Sandbox Code Playgroud)

我的CSS看起来像这样:

#s0 {
  border: 1px solid;
  background-color: yellow;
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!!

Dav*_*mas 5

节点的样式位于styles属性中,例如:

e.target.style.backgroundColor;
Run Code Online (Sandbox Code Playgroud)

但是,这仅适用于使用内联style属性声明的样式.如果使用样式表分配CSS(应该是),则需要使用:

window.getComputedStyle(e.target, null).backgroundColor;
Run Code Online (Sandbox Code Playgroud)

遗憾的是,Internet Explorer没有实现该getComputedStyle()选项,而是提供currentStyle(请注意,它们不支持e.target,我认为,至少在8之前的版本中?).我没有要测试的Internet Explorer,但是文档建议应该使用它:

var e = window.event ? window.event : e,
    elementNode = e.target !== null ? e.target : e.srcElement;
elementNode.currentStyle.backgroundColor;
Run Code Online (Sandbox Code Playgroud)

参考文献: