我想要弹出一个警报,每当我单击它时,它都会显示表格单元格的背景。我似乎无法找到或弄清楚如何获取背景颜色。
我的表格单元格如下所示:
<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,但是文档suggest应该使用它:
var e = window.event ? window.event : e,
elementNode = e.target !== null ? e.target : e.srcElement;
elementNode.currentStyle.backgroundColor;
参考:
-
currentStyle.
-
Element.style.
-
window.getComputedStyle().
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)