Javascript DOM style.backgroundColor 无法正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14153928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:51:19  来源:igfitidea点击:

Javascript DOM style.backgroundColor not working properly

javascripthtmldomjavascript-eventsonclick

提问by Majster

my problem is as it follows:

我的问题如下:

I have a piece of javascript code which generates a "new" document using document.writeand at first I write the entire heading of the web page. In that head I have a bit of CSS code which looks like this:

我有一段 javascript 代码,它使用生成一个“新”文档document.write,首先我编写了网页的整个标题。在那个头脑中,我有一些 CSS 代码,如下所示:

<style type='text/css'> 
.black {background-color: black;} 
.white {background-color: #ffffff;} 
td {width:50px; height:50px;} 
</style>

And javascript draws a table in the body section. Writing code is basically two forloops which draw a chess board. But that doesnt even matter. Every tdelement gets a class blackor whiteby which it gets properly coloured. And every tdgets a onclick='changeBg(this)'attribute.

并且 javascript 在 body 部分绘制一个表格。编写代码基本上是for绘制棋盘的两个循环。但这甚至无关紧要。每个td元素都有一个类blackwhite通过它得到正确的颜色。每个td都有一个onclick='changeBg(this)'属性。

Here is where the problem comes to life. I can not access the background color of the element that gets clicked. Function looks like so:

这就是问题出现的地方。我无法访问被点击的元素的背景颜色。函数看起来像这样:

function changeBg(element)
{
    alert(element.style.backgroundColor);
    element.style.backgroundColor = "red";
}

At first I alert the color of the current element. It always alerts a blank notification. After I change the color to red and click on the element again it alerts red. The td's are coloured in the browser and if I inspect them with firebug the have background-color: black | white;

起初我警告当前元素的颜色。它总是提醒一个空白的通知。在我将颜色更改为红色并再次单击该元素后,它会发出警报red。的td在浏览器中是彩色的,如果我用萤火虫检查它们,则有background-color: black | white

What am I missing and how to fix this? I have realised that if I set tdcolor when creating them using style="color: black | white"; it works but then I dont know to which class they belong.

我错过了什么以及如何解决这个问题?我已经意识到,如果我td在使用创建它们时设置颜色style="color: black | white";它有效,但后来我不知道它们属于哪个班级。

回答by techfoobar

You can get the currently applied styleusing window.getComputedStyle- Docs

您可以使用- Docs获取当前应用的样式window.getComputedStyle

function changeBg(element) {
    alert(window.getComputedStyle(element).backgroundColor);
    element.style.backgroundColor = "red";
}