style.backgroundColor无法正常工作

时间:2014-05-22 06:58:07

标签: javascript css

我一直在尝试更改点击事件中元素的背景颜色。 但是代码似乎不起作用..

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 ..

2 个答案:

答案 0 :(得分:2)

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");

说明

  

Window.getComputedStyle()方法给出了所有CSS的值   应用活动样式表后元素的属性   解决这些值可能包含的任何基本计算。

对于您的情况,您的功能应如下所示:

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背景字符串。

答案 1 :(得分:0)

您可以使用element的className属性。

您的javascript代码将是这样的

function place(ctrl)
{
    ctrl.className =(ctrl.className=="white"?"black":"white");
}

查看小提琴here