Home >Web Front-end >JS Tutorial >How to get css properties in js

How to get css properties in js

coldplay.xixi
coldplay.xixiOriginal
2020-11-09 14:49:471775browse

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);//弹出空的对话框
}
}

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
}
}

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

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

alert(a.backgroundColor);//red

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);

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!

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