我一直在尝试更改点击事件中元素的背景颜色。 但是代码似乎不起作用..
HTML
<td class="white" onclick="place(this,1,2)"></td>
风格
<style>
.black{
width: 70px;
height: 70px;
background-color:black;
}
.white{
width: 70px;
height: 70px;
background-color:white;
}
</style>
下面是使用的 javascript 函数..
function place(domObj,row,col){
alert(domObj.style.backgroundColor);
}
警报返回 null..
最佳答案
domObj.style
仅返回使用 style
属性内联设置的样式。
对于来自 CSS 文件的样式,您需要使用类似:window.getComputedStyle
示例来自 documentation :
var elem = document.getElementById("elem-container"); // this is your domObj
var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
描述:
The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
对于您的情况,您的函数应如下所示:
function place(domObj,row,col){
alert(window.getComputedStyle(domObj,null).getPropertyValue("background-color"));
}
更新
自 Internet Explorer 7 起,颜色始终以 RGB 值返回。无法直接返回它,但您可以使用以下代码片段将其从 RGB 转换为十六进制:
bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
其中 bg
是 RGB 背景字符串。
关于javascript - style.backgroundColor 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23799824/