Javascript DOM style.backgroundColor无法正常工作

Maj*_*ter 5 html javascript dom onclick javascript-events

我的问题如下:

我有一段javascript代码生成一个"新"文档使用document.write,起初我写了网页的整个标题.在那个脑袋里,我有一些CSS代码,看起来像这样:

<style type='text/css'> 
.black {background-color: black;} 
.white {background-color: #ffffff;} 
td {width:50px; height:50px;} 
</style>
Run Code Online (Sandbox Code Playgroud)

并且javascript在body部分绘制一个表.编写代码基本上是两个for绘制棋盘的循环.但这甚至不重要.每个td元素都有一个类black或者white它被正确着色.每个人td都有一个onclick='changeBg(this)'属性.

这就是问题变为现实的地方.我无法访问被点击的元素的背景颜色.功能如下:

function changeBg(element)
{
    alert(element.style.backgroundColor);
    element.style.backgroundColor = "red";
}
Run Code Online (Sandbox Code Playgroud)

首先,我提醒当前元素的颜色.它始终警告空白通知.将颜色更改为红色并再次单击该元素后,它会发出警报red.该td的是彩色的浏览器,如果我检查他们的萤火虫有background-color: black | white;

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

tec*_*bar 6

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

function changeBg(element) {
    alert(window.getComputedStyle(element).backgroundColor);
    element.style.backgroundColor = "red";
}
Run Code Online (Sandbox Code Playgroud)