每当我使用这种类型的代码来查找元素的背景颜色时,它总是返回“”。
<style><!--From external stylesheet-->
#divexample{
background-color:#4345C7;
}
</style>
<div id="divexample"></div>
<script type="text/javascript">
var bgColor=document.getElementById("divexample").style.backgroundColor;
alert(bgColor);
</script>
答案 0 :(得分:0)
您可能需要考虑使用jQuery
。然后,您可以轻松获得backgroundColor
:
var bgColor = $("#divexample").css("backgroundColor");
答案 1 :(得分:0)
检查一下:
http://jsfiddle.net/h28zdhtc/4/
<style>
div {
width: 60px;
height: 60px;
margin: 5px;
float:left;
}
div.div1{background-color:blue;}
div.div2{background-color:black;}
div.div3{background-color:green;}
div.div4{background-color:red;}
</style>
<span id="result"> </span>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<div class="div4"></div>
<script>
$( "div" ).click(function() {
var color = $( this ).css( "background-color" );
$( "#result" ).html( "That div is <span style='color:" +
color + ";'>" + color + "</span>." );
});
</script>
有关详细信息,请参阅: