JavaScript 如何获取CSS属性的当前值
在本文中,我们将看到如何使用JavaScript获取CSS属性的当前值。要获取元素的CSS样式,我们将使用getComputedStyle()方法。
getComputedStyle()方法 用于获取指定元素的所有计算后的CSS属性和值。计算后的样式显示了应用于多个来源的样式后的元素。它返回一个CSSStyleDeclaration对象。
语法:
window.getComputedStyle(element, pseudoElement);
示例 1: 在此示例中,我们将使用getComputedStyle()方法获取CSS属性的当前值。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to Get Current Value of a
CSS Property in JavaScript?
</title>
<style type="text/css" id="GFG">
body {
text-align: center;
}
h1 {
color: green;
}
#box {
width: 250px;
height: 100px;
line-height: 100px;
color: white;
background-color: rgb(0, 128, 0);
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h3>
How to Get Current Value of a
CSS Property in JavaScript?
</h3>
<div id="box"></div>
<script>
let id = document.getElementById("box");
let stle = window.getComputedStyle(id);
document.querySelector('div').textContent
= ('background-color: '
+ stle.getPropertyValue('background-color'));
</script>
</body>
</html>
输出:
示例2: 在这个示例中,我们可以使用JavaScript中的window.getComputedStyle()方法来获取CSS属性的当前值。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
How to Get Current Value of a
CSS Property in JavaScript?
</title>
<style>
body {
text-align: center;
}
#content {
width: 150px;
padding: 30px 20px;
background-color: green;
margin: auto;
}
</style>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
How to Get Current Value of a
CSS Property in JavaScript?
</h3>
<div id="content">Welcome to GFG</div>
<br>
<button onclick="Fun()">Get CSS Value</button>
<pre id="CSSVal"></pre>
<script>
function Fun() {
const element = document.querySelector("#content");
const value = window.getComputedStyle(element)
.getPropertyValue('background-color');
document.getElementById("CSSVal").innerHTML = value;
}
</script>
</body>
</html>
输出: