In the early days of learning JS, there has been a question, get the value of the element style, not directly use
obj.style.left
Or something like that, can you get it? However, the use of such a way, sometimes can be obtained, and sometimes can not be obtained, has been puzzled unceasingly, but because of the previous study attitude problem, also did not delve into, today dedicated to spend a bit of time to collate this knowledge.
Style
First of all, we need to make clear the following three types of styles
- inline style: the inline style, written directly in the DOM element's style property
- Embedding styles: styles written in <style></style> in HTML pages
- external styles: styles in CSS files introduced by the link tag
Priority: inline > Embed > External
First, write an example to test the value of the element style by using the style method, where a style is written in the row, a style is written in the style tag, and a style is introduced by link
// index.css.box { background-color: orange; }
// javascriptvar box = document.getElementsByClassName(‘box‘)[0];console.log(box.style.width);console.log(box.style.height);console.log(box.style.backgroundColor);
The results are as follows:
‘100px‘‘‘‘‘
So we can see that the height value and the BackgroundColor value are not obtained, so we get the following conclusion:
Style can only get values of inline styles and cannot get values for inline styles and external styles
What about the values of the embedded style and the external style, see the code below
// currentStyle: IE下获取元素样式的值if ( box.currentStyle ) { console.log( ‘this is IE.‘ ); console.log( box.currentStyle.width ); console.log( box.currentStyle.height ); console.log( box.currentStyle.backgroundColor );} else { // chorme and firefox console.log( document.defaultView.getComputedStyle(box, false).width ); console.log( document.defaultView.getComputedStyle(box, fasle).height ); console.log( document.defaultView.getComputedStyle(box, false).backgroundColor );}
Output results
‘this is IE.‘‘100px‘‘200px‘‘orange‘
Test them in IE, Chrome, Firefox, and finally get all the properties. Very good, so we can draw a conclusion
The best way to get an element style value is through obj.currentStyle
or
document.defaultView.getComputedStyle( obj, false )
In the same way, where the former applies to IE, the latter for Chrome and Firefox
So we can write a way to get the element style value.
var getStyle = function(obj, key) { return obj.currentStyle ? obj.currentStyle[key] : document.defaultView.getComputedStyle( obj, false )[key];}
Native JS Gets the element style value