js中style,currentStyle和getComputedStyle的区别

本文介绍了JavaScript中获取元素样式的多种方法,包括style属性、currentStyle和getComputedStyle,并提供了一个兼容不同浏览器的自定义函数。

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

<style>
body{margin:0 auto;text-align:center;}
div{position:relative;left:10px;}
</style>
<div id="pic1">
<img src="http://pic1.xihuan.me/edr/196__/t02362982432fa1b14e.jpg">
</div>
<script>
var dom1 = document.getElementByIdx_x('pic1');
console.log(dom1.style.left);
</script>


控制台中显示为空。

查询了相关资料发现问题如下:

[color=red]style只能获取元素的内联样式[/color],内部样式和外部样式使用style是获取不到的。
[color=red]currentStyle[/color]可以弥补style的不足,[color=red]但是只适用于IE[/color]。
[color=red]getComputedStyle[/color]同currentStyle作用相同,但是适用于[color=red]FF、opera、safari、chrome[/color]。

写了个getStyle的自定义函数,来兼容ie和其他浏览器,使用getStyle来获取页面中元素的样式,问题解决。
getElementStyle: function(el,attr){
//获取el当前的attr样式,解决ie问题
return el.currentStyle?el.currentStyle[attr]:getComputedStyle(el,null)[attr];
}
获取后返回10px。

注意:
currentStyle和getComputedStyle只能用于获取页面元素的样式,不能用来设置相关值。
如果要[color=red]设置相应值,应使用style。[/color]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值