如何获取页面元素的某一个样式

本文介绍了一种跨浏览器兼容的方法来获取元素的样式属性,无论是直接定义在元素的style属性中还是通过类名设置。该方法利用了currentStyle属性和getComputedStyle函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>getStyle</title>
<style>
.defaultCls{
width:200px;
height:300px;
border:1px solid windowtext;
}
</style>
<script>
function check(){
var obj = document.getElementById("content");
alert(getStyle(obj,"width"));
}

function getStyle(obj,styleName){
if (styleName==null){
return "";
}
var str = styleName;
var pos = str.indexOf("-");
while(pos>=0){
if (pos == str.length - 1){
str = str.substring(0,pos);
}
else if(pos == str.length - 2){
str = str.substring(0,pos)+str.substring(pos + 1).toUpperCase();
}
else{
str = str.substring(0,pos)+str.substring(pos + 1,pos + 2).toUpperCase()+str.substring(pos + 2);
}
pos = str.indexOf("-");
}
var style = "";
if (obj.currentStyle)
style = obj.currentStyle[str];
else if (window.getComputedStyle)
style = document.defaultView.getComputedStyle(obj,null).getPropertyValue(str);
return style || "";
}
</script>
</head>
<body>
<div id="content" style="font-size:12px" class="defaultCls">sfsd
</div>

<input type="button" value="check" onclick="check()" />
</body>
</html>

平常我们都是使用dom.style.display这种方式去获取某一个样式,可这样就会有个问题,如果我的样式是定义在class中的,这种方式就无能为力了。
还好浏览器提供给我们解决方法,那就是使用currentStyle属性或者是document.defaultView.getComputedStyle函数,不同浏览器的处理方式不一样。
这样我们就可以获取到我们想要的结果,不论是定义在style中还是class中。
上面的代码在ie以及Firefox中测试通过,其他浏览器未测试。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值