javascript - style.backgroundColor 不工作

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

最佳答案

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/

相关文章:

javascript - Angular 中的幻灯片放映 css 过渡

javascript - 按钮在改变位置时不起作用

javascript - ES6/React 包 - 尝试导入时导出的类未定义(使用 webpack 构建)?

HTML/CSS : default borders iframe

javascript - 如何展开或关闭 html/JS 中的内容 - 总是分配给不同的 id

javascript - 谷歌API选择器: google is not defined

html - 减少图像与其底层文本之间的空间

html - 手机浏览器工具栏隐藏时高度100%

javascript - 如何使用 two.js 创建圆形热点?

javascript - 选择非 "spanned"的文本