检索表中元素的背景色

Retrieve the background color of an element in a table

本文关键字:背景色 元素 检索      更新时间:2023-09-26

在检索/确定之前使用css着色的html表中的单元格的背景色时遇到问题。我希望能够使用javascript检索该颜色,并将其存储到一个变量中,以便在我的代码中进一步使用(未显示)。

以下是我试图在一个简单的范围内做的事情:http://jsfiddle.net/adtsolutions/6P629/.代码也提供如下:

HTML:

<body>
<table>
    <tr>
        <td>Hello there</td>
        <td id="HDD">I want to know this cell's color</td>
    </tr>
</table>

CSS:

TD {
    TEXT-ALIGN: CENTER;
    BORDER: 2PX SOLID BLACK; 
    BORDER-COLLAPSE: COLLAPSE; 
    BACKGROUND-COLOR: #D0A9F5; 
}

JS:

//document.getElementById("HDD").style.background="#D0A9F5"
var myColor = document.getElementById("HDD").style.background;
alert(myColor);

现在,当我试图显示变量"myColor"的内容时,我总是得到一个"空白",它应该是背景色。我注意到,如果我取消对javascript中的第一行的评论,myColor会清楚地说出我希望它能显示的内容。有没有想过我可能做错了什么,或者为什么只有在javascript中内联定义背景颜色时才有效?非常感谢您的建设性帮助!

您可以使用.getComputedStyle(),它将返回rgb颜色:

var theCSSprop = window.getComputedStyle(document.getElementById("HDD"), null).getPropertyValue("background-color");

jsFiddle示例

您可以使用jQuery并使用css()方法,其中您可以使用$('#selector').css('background-color')$('#selector').css('backgroundColor'),如下所示:

<div class="test">hello</div>

CSS:

.test {
    background-color:#fff;
    width:100px;
    height:100px;
}

JS:

$( document ).ready(function() {
  var c = $('.test').css( "backgroundColor" );
    alert(c);
});

JSFiddle在这里:http://jsfiddle.net/E4eBJ/

关于.css()的更多信息,请访问jQuery文档网站:http://api.jquery.com/css/

尝试将"…style.background;"更改为"…style.background color;"我不太懂JavaScript;但是,如果您在JavaScript中引用CSS元素,那么背景颜色可能是一个更准确的属性。

JavaScript

var Color = document.getElementById("HDD");
    var myColor = window.getComputedStyle(Color,null).getPropertyValue('background-Color');
    alert(myColor);

Fiddle示例:http://jsfiddle.net/6P629/23/

要了解更多信息,请参阅以下链接window.getComputedStyle