Everyone knows that getting the style of an element in JavaScript native operation is a relatively common thing in actual operation. Here I would like to introduce the method of getting the css style. I hope it can help some people in need. If you are lucky, If someone sees a better way, you are welcome to suggest it! ! !
1. Get the inline element style:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>js获取外部样式</title></head><body> <div id="div" style="width:200px;height:200px;border:3px solid cyan;"></div></body><script> //获取行间样式 var div = document.getElementById(‘div‘); var width = div.style.width; alert(width);//200px</script></html>
In the JS code, alert will pop up the width of the div element as 200px; the purpose of getting the width of the element is achieved, but this simple method It is only suitable for obtaining the inline element style of the element, and cannot obtain the internal style and external style. In the project, the solution of writing inline elements is not recognized by everyone, so this method is just for everyone to understand.
2. Obtaining non-interline style elements:
If the element style is not interline style, the above method cannot be used to obtain the element style, and another method needs to be used:
<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>js获取内部部样式</title> <style> #div{ width: 200px; height: 200px; border:3px solid cyan; } </style></head><body> <div id="div""></div></body><script> var div = document.getElementById(‘div‘); //获取div的width var width = window.getComputedStyle(div,null).width; alert(width);//200px //修改div的width div.style.cssText=‘width:300px;‘</script></html>
In the above code, window.getComputedStyle('Element',null).'Style' is used. The compatibility of this method: Firefox and Google IE9 obtain the calculated style, but what needs to be noted here is the use The value obtained by this method is in read-only mode and cannot be modified, so the style.cssText method is used to modify its properties. Here you need to pay attention to the writing method.
3. Compatibility:
The unspoken rule in the previous paragraph is that all good things cannot be used universally. Yes, you guessed it right, the willful IE cannot use the above method, but IE has its own method called currentStyle. The usage is the same, so I won’t go into details. I will write it directly below. The compatible code that has been processed is as follows:
var div = document.getElementById(‘div‘);if (div.currentStyle) { console.log(div.currentStyle.width); }else{ console.log(getComputedStyle(div,null).width); } 方法封装: function getStyle(obj,name){ if (obj.currentStyle) { return obj.currentStyle[name]; }else{ return getComputedStyle(obj,false)[name]; } }
Native JS gets the HTML style and modifies it
For more native JS to get the HTML style and modifies it, please pay attention to the PHP Chinese website for related articles!