---
title: "js中style,currentStyle和getComputedStyle的区别"
author: "tanwenEyE"
date: "2014-05-28T17:40:07Z"
tags: []
categories: ["Web前端"]
slug: "js-style-currentstyle-getcomputedstyle"
draft: false
lastmod: "2014-05-28T17:40:07Z"
id: 2072850
url: "https://tanweneye.iteye.com/blog/2072850"
---

\[code="html"]

![](http://pic1.xihuan.me/edr/196__/t02362982432fa1b14e.jpg)

\[/code] 控制台中显示为空。 查询了相关资料发现问题如下： \[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]