Use javascript to get the style of an element from an external css file

I have html like this:

<html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> alert(document.getElementById('test').style.display); </script> </body> </html> 

.Css style:

 div { display:none; } 

I expect js to return "none", but instead return an empty string. Is there any way to solve this problem?

+6
javascript html css
source share
3 answers

This will work for standards compliant browsers (not IE - currentStyle / runtimeStyle).

 <body> <div id="test">Testing</div> <script type="text/javascript"> window.onload = function() { alert(window.getComputedStyle(document.getElementById('test'),null).getPropertyValue('display')); } </script> </body> 

+5
source share

Since the mapping is not set directly as a property of the style, you will not get this using the above code. You should get the calculated value.

You can link to this page. Get styles.

To get the value

 var displayValue = getStyle("test", "display"); function getStyle(el,styleProp) { var x = document.getElementById(el); if (x.currentStyle) var y = x.currentStyle[styleProp]; else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); return y; } 
+3
source share

CSS is not loaded yet. Wrap your JavaScript in a "finished" event.

<body onload="alert(document.getElementById('test').style.display);">

Does this work for you?

0
source share

All Articles