使用javascript,我如何得到一个表格单元格的背景颜色,当我点击它

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

本文关键字:背景 单元格 颜色 表格 何得 javascript 使用 一个      更新时间:2023-09-26

我想有一个警报弹出,显示我的背景表格单元格每当我点击它。我似乎就是找不到或想不出如何抓取背景色。

我的表格单元格是这样的:

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

我的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.
}

我的CSS是这样的:

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

任何帮助将非常感激!!

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

e.target.style.backgroundColor;

然而,这只适用于那些用内联style属性声明的样式。如果CSS是使用样式表分配的(应该如此),则需要使用:

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

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;

引用:

  • currentStyle .
  • Element.style .
  • window.getComputedStyle() .

您可以通过Jquery css()函数轻松实现

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

要了解更多细节,请查看以下示例