getComputedStyle()方法用於獲取所有計算的CSS屬性和指定元素的值。在應用來自多個來源的樣式之後,將使用計算樣式顯示元素。 getComputedStyle()方法返回CSSStyleDeclaration對象。
用法:
window.getComputedStyle(element, pseudoElement)
參數:
- element:用於獲取計算樣式的元素
- pseudoElement:要獲取的pseudo-element。這是一個可選參數。
例:返回div中文本的font-family。
<!DOCTYPE html>
<html>
<head>
<title>
HTML | DOM Window getComputedStyle() Method
</title>
<style>
div {
color:white;
text-align:justify;
}
</style>
</head>
<body>
<center>
<p>
<button onclick="myFunction()">
Try it
</button>
</p>
<div id="test" style="height:100px;
background-color:green;
font-size:50px;
padding-left:140px;
padding-top:50px;">
Geeks for Geeks
</div>
<p>
The computed font-family of text
in the test div is:
<span id="demo"></span>
</p>
<script>
function myFunction() {
var elem = document.getElementById("test");
var theCSSprop =
window.getComputedStyle(
elem, null).getPropertyValue("font-family");
document.getElementById("demo").innerHTML =
theCSSprop;
}
</script>
</center>
</body>
</html>
輸出:
在點擊按鈕之前:
單擊按鈕後:
支持的瀏覽器:下麵列出了Window getComputedStyle()方法支持的瀏覽器:
- 穀歌瀏覽器11.0
- Internet Explorer 9.0
- Firefox 4.0
- Opera 11.5
- Safari 5
相關用法
- Javascript Window print()用法及代碼示例
- Javascript Window confirm()用法及代碼示例
- Javascript Window prompt()用法及代碼示例
- Javascript Window scrollTo()用法及代碼示例
注:本文由純淨天空篩選整理自Vijay Sirra大神的英文原創作品 JavaScript | Window getComputedStyle() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。