开发者

How come changing styles with document.getElementById() works with styles set inline but not internally? [duplicate]

This question already has answers here: Reading non-inline CSS style info from Javascript (4 answers) Closed 8 years ago.

If I set a style inline like this:

<div id='myMenu' style='background开发者_如何学编程-color:red'></div>

Then in JS call

alert("document.getElementById('myMenu')style.backgroundColor");

The result alert box would report "red"

However if I set the style internally in the via a class or id

<style type='text/css'>    
.menu {
       background-color:red;
    }
</style>

Then the alert reports blank.

Will styles with .getElementById only work with inline style? Seems very limiting...


You are not setting the style attribute for the element but instead you are setting a class.

So...

alert(document.getElementById("myMenu").className);


You can use jQuery to read the "real" background color, no matter how it was assigned:

alert($("#myMenu").css("background-color"));

No idea how it's doing it, but I've checked it now and it works. :)

You can download most recent version of jQuery from the official site: http://docs.jquery.com/Downloading_jQuery

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜