风格.背景颜色不工作



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

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

        }

alert返回null.

domObj.style只返回使用style属性内联设置的样式。

对于来自CSS文件的样式,您需要使用以下内容:window.getComputedStyle

文档中的例子:

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

你可以使用元素的className属性。

你的javascript代码应该是这样的

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

看这里的提琴

最新更新