分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

css样式获取,style,currentStyle,getComputedStyle

发布时间:2023-09-06 01:22责任编辑:胡小海关键词:style

对于css样式的获取问题,对于行内样式,我们可以用style来获取,但是对于内嵌和外部样式的话,style就心有余和力不足了。它是获取不到这些样式的

此时就只有currentStyle和getComputedStyle上阵了。

currentStyle是只兼容各种IE的,但是不兼容火狐,谷歌的,而getComputeStyle的话是可以兼容火狐,谷歌,和IE9+的。(以下测试均在谷歌和IE下)

对于行内样式:

<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<!-- <link href="test.css" rel="stylesheet"> --> ???<script type="text/javascript" src="test.js" defer="defer"></script> ???<title>Document</title></head><style type="text/css"></style><body> ???<div class="wrap" style=" ???width:100px; ???height:100px; ???background-color:black;"> ???</div></body></html>

此时用这着三种方法:

var oWrap = document.getElementsByTagName("div")[0];window.onload = function (){ ???console.log(oWrap.style.width); ???console.log(oWrap.currentStyle.width); ???console.log(getComputedStyle(oWrap,null).width);}

得到的结果是:

把报错的,也就是currentStyle注释掉,就会得到:

情理之中。因为currentStyle时不兼容谷歌的

 然后改成内嵌样式的话:

结果也在意料之中:

再加上注释了,结果是:

外部样式表的话,结果也是一样的。

然后IE的话,

IE8的话是不支持getComputedStyle。而IE9+是支持的。

外部样式IE8:

外部样式IE9:

最后完全符合结果。

结论:

1.style只支持行内样式,对于其他样式引入方式一律不好用。

2.currentStyle和getComputedStyle支持各种样式引入方式。但存在兼容性问题。

3.currentStyle兼容IE,不兼容谷歌,火狐等浏览器,会报错。

4.getComputedStyle兼容谷歌,火狐,IE9+,不兼容IE8以下,包括IE8。

注意:

1.currentStyle的使用方式是:元素.currentStyle("样式名")或者元素.currentStyle.样式名。

2.getComputedStyle是全局的,使用方式是:getComputedStyle("元素",“伪类”)["样式名"]或者getComputedStyle("元素",“伪类”).样式名。

css样式获取,style,currentStyle,getComputedStyle

原文地址:http://www.cnblogs.com/178-533/p/7783944.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved