-
Notifications
You must be signed in to change notification settings - Fork 118
/
js中获取css样式属性值.html
43 lines (42 loc) · 1.36 KB
/
js中获取css样式属性值.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
40
41
42
43
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>js中获取css样式属性值</title>
<style type="text/css">
#div1{
width:200px;
height:200px;
background:#ddd;
}
#div1:before{
content:'我是伪元素内容';
color:#000;
}
</style>
</head>
<body>
<div id="div1" style="width:100px;background-color:green;"></div>
</body>
<script type="text/javascript">
window.onload=function(){
var oDiv=document.getElementById('div1');
//使用style属性只能获取到内联样式
console.log(oDiv.style.backgroundColor);
console.log(getStyle(oDiv,'background'));
console.log(getStyle(oDiv,'color',':before'));
}
function getStyle(obj, attr,pseudoElt=false){
//只适用于IE
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
//适用于FF,Chrome,Safa
return getComputedStyle(obj,pseudoElt)[attr];
}
//return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj,pseudoElt)[attr]
}
//详细链接 https://www.cnblogs.com/zuobaiquan01/p/8461754.html
</script>
</html>