Home  >  Article  >  Web Front-end  >  How to get css attribute value in js

How to get css attribute value in js

青灯夜游
青灯夜游Original
2021-07-07 15:24:308166browse

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".

How to get css attribute value in js

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

obj.style:

This method can only get the value written in the style attribute, but cannot get the value defined in 4d8f948b60abbe82b0444ae22607a153The 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 and getComputerStyle

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn