[英]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: 我的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.
}
My CSS looks like this: 我的CSS看起来像这样:
#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: 节点的样式位于styles属性中,例如:
e.target.style.backgroundColor;
However this works only for those styles declared with the in-line style
attribute. 但是,这仅适用于使用内联style
属性声明的style
。 If CSS is assigned (as it should be) using a stylesheet, you'll need to use: 如果使用样式表分配CSS(应该是),则需要使用:
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?). 遗憾的是,Internet Explorer没有实现getComputedStyle()
选项,而是提供currentStyle
(介意,他们也不支持e.target
,我认为,至少在8之前的版本中?)。 I don't have Internet Explorer with which to test, but the docs suggest that it should be used: 我没有要测试的Internet Explorer,但是文档建议应该使用它:
var e = window.event ? window.event : e,
elementNode = e.target !== null ? e.target : e.srcElement;
elementNode.currentStyle.backgroundColor;
References: 参考文献:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.