Home > Web Front-end > JS Tutorial > body text

How to get css properties in js

coldplay.xixi
Release: 2020-11-17 18:16:04
Original
1728 people have browsed it

JS method to obtain css attributes: use the [getComputedStyle(div)] method to obtain, the code is [var a = document.defaultView.getComputedStyle(div);].

How to get css properties in js

【Recommended related articles: vue.js

How to get css properties in js:

When using native js for development, you should encounter the need to get css properties, and then find out It seems that direct access is not possible. Here are two ways to get css attributes in native js

Direct acquisition will fail. For example

window.onload = function() {
var but = document.getElementById('button');
var div = document.getElementById('getStyle');
but.onclick = function() {
alert(div.style.width);//弹出空的对话框
}
}
Copy after login

Use the getComputedStyle(div) method

Usage example

window.onload = function() {
var but = document.getElementById('button');
var div = document.getElementById('getStyle');
but.onclick = function() {
var a = document.defaultView.getComputedStyle(div);
alert(a.width);//100px
}
}
Copy after login

Notes

1. What you get is the style calculated by the browser. If you get the background, you will get the following results

alert(a.background);//reb(255,0,0) none repeat sroll 0% 0% / auto padding-box border-box
Copy after login

So please indicate clearly what you want The obtained style is like this

alert(a.backgroundColor);//red
Copy after login

2. Do not have spaces when writing the name

'div' cannot be 'div'

3. Do not get unset Style, incompatible

Solution to compatibility: IE8 and lower versions cannot use the getComputedStyle method, but use the currenrStyle method

a = div.currentStyle;
alert(a.width);
Copy after login

Related free learning recommendations:javascript(Video)

The above is the detailed content of How to get css properties in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!