-
Notifications
You must be signed in to change notification settings - Fork 4
/
计算样式获取.html
39 lines (38 loc) · 1.17 KB
/
计算样式获取.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html>
<html>
<head>
<title>Computed Styles Example</title>
<style type="text/css">
#myDiv {
background-color: blue;
width: 100px;
height: 200px;
}
</style>
</head>
<body>
<div
id="myDiv"
style="background-color: red; border: 1px solid black"
></div>
</body>
<script>
let myDiv = document.getElementById("myDiv");
let computedStyle = document.defaultView.getComputedStyle(myDiv, null);
console.log(computedStyle.backgroundColor); // "red"
console.log(computedStyle.width); // "100px"
console.log(computedStyle.height); // "200px"
console.log(computedStyle.border); // "1px solid black"(在某些浏览器中)
/* 兼容写法 */
function getStyleByAttr(obj, name) {
return window.getComputedStyle
? window.getComputedStyle(obj, null)[name]
: obj.currentStyle[name];
}
let node = document.getElementById("myDiv");
console.log(getStyleByAttr(node, "backgroundColor"));
console.log(getStyleByAttr(node, "width"));
console.log(getStyleByAttr(node, "height"));
console.log(getStyleByAttr(node, "border"));
</script>
</html>