JavaScript强化教程——style、currentStyle、getComputedStyle区别介绍

本文为 H5EDU 机构官方 HTML5培训 教程,主要介绍:JavaScript强化教程 —— style、currentStyle、getComputedStyle区别介绍css

style、currentStyle、getComputedStyle区别介绍
样式表有三种方式
内嵌样式(inline Style) :是写在Tag里面的,内嵌样式只对全部的Tag有效。

内部样式(internal Style Sheet):是写在HTML的里面的,内部样式只对所在的网页有效。

外部样式表(External Style Sheet):若是不少网页须要用到一样的样式(Styles),将样式(Styles)写在一个以.css为后缀的CSS文件里,而后在每一个须要用到这些样式(Styles)的网页里引用这个CSS文件。 最经常使用的是style属性,在JavaScript中,经过document.getElementById(id).style.XXX就能够获取到XXX的值,但意外的是,这样作只能取到经过内嵌方式设置的样式值,即style属性里面设置的值。



解决方案:引入currentStyle,runtimeStyle,getComputedStyle style 标准的样式,多是由style属性指定的!

runtimeStyle 运行时的样式!若是与style的属性重叠,将覆盖style的属性!

currentStyle 指 style 和 runtimeStyle 的结合! 经过currentStyle就能够获取到经过内联或外部引用的CSS样式的值了(仅限IE) 如:document.getElementById("test").currentStyle.top

要兼容FF,就得须要getComputedStyle 出马了

注意: getComputedStyle是firefox中的, currentStyle是ie中的. 好比说

<style>
#mydiv {
     width : 300px;
}
</style>
则:

var mydiv = document.getElementById('mydiv');
if(mydiv.currentStyle) {
      var width = mydiv.currentStyle['width'];
      alert('ie:' + width);
} else if(window.getComputedStyle) {
      var width = window.getComputedStyle(mydiv , null)['width'];
      alert('firefox:' + width);
}
另外在FF下还能够经过下面的方式获取

1
2
document.defaultView.getComputedStyle(mydiv,null).width;
window.getComputedStyle(mydiv , null).width;

点击进入JavaScript强化教程
html

相关文章
相关标签/搜索