![](/img/trans.png)
[英]How do I change the background color of an HTML table cell with javascript?
[英]Using javascript, how do I get the background color of a table cell when I click on it?
我希望弹出一个警告,只要我点击它就会显示表格单元格的背景。 我似乎无法找到或弄清楚如何抓住背景颜色。
我的表格单元格如下所示:
<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
属性声明的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;
参考文献:
您可以通过Jquery css()函数轻松完成
jQuery(document).ready(function(){
$(this).click(function () {
var color = $(this).css("background-color");
alert(color);
});
});
有关更多详细信息,请查看此示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.