JS method to obtain css attribute value: 1. Obtain through the style attribute of the element object, the syntax is "element object.style.property name"; 2. Through the getComputerStyle attribute, the syntax is "getComputerStyle.property name".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
This method can only get the value written in the style attribute, but cannot get the value defined in <style type='text /css'>
The properties inside
<style type=”text/css”> .ss{color:#cdcdcd;} </style> <div id=”css88″ class=”ss” style=”width:200px; height:200px; background:#333333″>JS获取CSS属性值 </div> <script type=”text/javascript”> alert(document.getElementById(“css88″).style.width);//200px alert(document.getElementById(“css88″).style.color);//空白 </script>
obj.currentStyle is only supported by IE, while getComputerStyle is supported in FireFox. This method accepts two parameters: To get the calculated style of the element and a pseudo-element string (such as ";after"). If pseudo-element information is not required, the second parameter can be null. This method returns a CSSStyleDeclaration object containing all calculated styles for the current element.
<html> <head> <title>计算元素样式</title> <style> #myDiv { width:100px; height:200px; } </style> <body> <div id ="myDiv" style=" border:1px solid black"></div> <script> var myDiv = document.getElementById("myDiv"); var computedStyle = document.defaultView.getComputedStyle(myDiv, null); alert(computedStyle.backgroundColor); //"red" alert(computedStyle.width); //"100px" alert(computedStyle.height); //"200px" alert(computedStyle.border); //在某些浏览器中是“1px solid black” </script> </body> </head> </html>
So it is estimated to be compatible with browsers. We can encapsulate a function to get the CSS attribute value of an element:
function getStyle(element, attr) { if(element.currentStyle) { return element.currentStyle[attr]; } else { return getComputedStyle(element, false)[attr]; } }
[Related recommendations: javascript learning tutorial 】
The above is the detailed content of How to get css attribute value in js. For more information, please follow other related articles on the PHP Chinese website!