简体   繁体   中英

Getting style of an element from css file with javascript

I wanna get a style of an element from css file with javascript. But, i just can getting only elements i enter style properties on javascript. I tried like this on Angular;

angular.element(document.getElementById("box")).css("width")

It's not worked. After, i tried like this;

document.getElementById("box").style

But it's not worked. How can i accomplish this?

This isn't an Angular issue, it's just how CSS and Javascript interact. You need to use getComputedStyle to read style properties that were defined in a CSS file.

 // This will work (because it's an inline style) console.log(document.getElementById('a').style.width) // This won't work (because the style was defined in css): console.log(document.getElementById('b').style.width) // getComputedStyle will work regardless of the source: console.log(window.getComputedStyle(document.getElementById('b')).width) 
 #b {width: 100px} 
 <div id="a" style="width: 100px">A</div> <div id="b">B</div> 

You cannot get css template rule values of elements calling style properties unless they were set *1. using inline style on html element level; or *2. the style property has been set using JavaScript

which does the same: writes to inline html style property of the target element.

the solution is to use the computed style instead:

as in : getComputedStyle(box,0).width

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM