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:30 8089browse

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 in4d8f948b60abbe82b0444ae22607a153The properties inside

 
JS获取CSS属性值

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.

  计算元素样式   

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