您的位置:首页 > Web前端 > CSS

JS 获取样式属性

2016-04-14 16:37 671 查看
摘要: JS获取CSS属性值方法有很多,开源昕昕这里介绍两种供大家学习
obj.style方法,这个方法只能JS只能获取写在html标签中的写在style属性中的值(style=”…”),看一下代码

<!doctype html>

<html>

<head>

<title>JS获取CSS属性值</title>
<style type=”text/css”>
<!–
.test{color:#cdcdcd;}
–>
</style>
</head>
<body>
<div id=”css88″ class=”test” style=”width:200px; height:200px; background:#333333″>JS获取CSS属性值</div>
<script type=”text/javascript”>
alert(document.getElementById(“css88”).style.width);//200px
alert(document.getElementById(“css88”).style.color);//空白
</script>
</body>
</html>

上面这个例子对id为”css88″的div设置了2种烦事的样式,包括style和外部样式class。
从alert出来的信息可以看到,document.getElementById(“css88”).style方法获取不到class为ss的属性和值。
那么这么样才能获取到class为ss的属性和值呢?
IE中使用的是obj.currentStyle方法,而FF是用的是getComputedStyle 方法。
具体案例如下:
方法一:

<!doctype html>

<html>

<head>

<title>JS获取CSS属性值</title>

<style>

#aa{height:300px;width:500px;border:solid 1px #5d5d5d;color:red;}

</style>

</head>

<body>

<div id="aa">0000</div>

<script>

function GetCurrentStyle (dd, prop) {

if (dd.currentStyle) {

return dd.currentStyle[prop];

}

else if (window.getComputedStyle) {

propprop = prop.replace (/([A-Z])/g, "-$1");

propprop = prop.toLowerCase ();

return document.defaultView.getComputedStyle (dd,null)[prop];

}

return null;

}

var dd=document.getElementById("aa");

alert(GetCurrentStyle(dd,"color"));

</script>

</body>

</html>

方法二(可将方法一简化为如下):

<script>

function getDefaultStyle(dd,attribute){

// 返回最终样式函数,兼容IE和DOM,设置参数:元素对象、样式特性

return dd.currentStyle?dd.currentStyle[attribute]:document.defaultView.getComputedStyle(dd,false)[attribute];

}

var dd=document.getElementById("aa");

alert(getDefaultStyle(dd,"color"));

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JS 获取 样式 属性