前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >getComputedStyle与currentStyle[通俗易懂]

getComputedStyle与currentStyle[通俗易懂]

作者头像
全栈程序员站长
发布2022-09-14 11:10:37
1.6K0
发布2022-09-14 11:10:37
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

本文参考https://developer.mozilla.org/en-US/docs/Web/API/Window.getComputedStyle

1.简介

getComputedStyle是window下的一个全局函数,可以获取元素真正使用的样式。

2.语法

代码语言:javascript
复制
var style = window.getComputedStyle(element[, pseudoElt]);

element是用于计算样式的dom节点,pseudoElt是一个用于匹配伪类的字符串,对于一般的dom元素来说,该参数应该被忽略或设置为null。需要注意的是在Gecko内核2.0(即Firefox4)之前该参数是必须的,对于其他主流浏览器来说该参数非必须,现在Firefox已经与其他浏览器一样将该参数设为optional,所以为了兼容性考虑,在没有匹配伪类的情况下,第二个参数最好传null。

还有一点需要说明的是,在Firefox3.6下,如果要获取框架样式(framed styles),必须要使用document.defaultView.getComputedStyle()而不能使用window.getComputedStyle()。那defaultView又是何物?其实defaultView返回的是document 对象所关联的 window 对象,如果没有,会返回 null。该属性为只读,IE 9 以下版本不支持 defaultView。

示例

代码语言:javascript
复制
<style>
 #elem-container{
   position: absolute;
   left:     100px;
   top:      200px;
   height:   100px;
 }
</style>

<div id="elem-container">dummy</div>
<div id="output"></div>  

<script>
  function getTheStyle(){
    var elem = document.getElementById("elem-container");
    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
    document.getElementById("output").innerHTML = theCSSprop;
   }
  getTheStyle();
</script>

3.与element.style的区别

首先,element.style属性不仅可读,而且可写,而getComputedStyle获取的样式是只读的;其次,element.style获取的样式是很有限定的,只能获取那些我们显式的设置的内联css样式,对于浏览器缺省设置、外部样式表以及内部样式表(位于 <head> 标签内部)都输出空字符串,而getComputedStyle会输出最终应用于该element上的最终样式,而不管该样式是内联的还是外联的还是浏览器默认的,总之不会输出空字符串。就拿csdn博客这个页面举例来说,我们注意一下document.body的background样式,如下图

getComputedStyle与currentStyle[通俗易懂]
getComputedStyle与currentStyle[通俗易懂]

body的内联样式为空,但在内部样式表中设置了background样式,在控制台下用分别用style和getComputedStyle检测结果,如下图所示

getComputedStyle与currentStyle[通俗易懂]
getComputedStyle与currentStyle[通俗易懂]

4.浏览器兼容性

桌面浏览器

getComputedStyle与currentStyle[通俗易懂]
getComputedStyle与currentStyle[通俗易懂]

IE9以下版本不支持getComputedStyle方法,恰如上文所说,IE9以下的document没有defaultView属性,所以只要是支持getComputedStyle的浏览器都可以调用document.defaultView.getComputedStyle()。所有版本的IE以及Opera的getComputedStyle方法都不支持伪类。

手机浏览器

getComputedStyle与currentStyle[通俗易懂]
getComputedStyle与currentStyle[通俗易懂]

手机浏览器对getComputedStyle方法基本都支持。

5.IE的currentStyle

如上文所说,IE8以及IE8以下的IE都不支持getComputedStyle方法,不过IE这坨奇葩提供了另一个属性element.currentStyle。到目前本文撰写为止,IE最新的浏览器IE11也保留该属性,也就是说IE9+的浏览器既可以使用getComputedStyle也可以使用element.currentStyle属性。element.currentStyle的示例如下:

代码语言:javascript
复制
document.body.currentStyle.getAttribute('backgroundColor')

getComputedStyle和element.currentStyle主要存在以下区别:

a.前者在很多浏览器上(except IE)都支持伪类,currentStyle完全不支持伪类;

b.前者使用getPropertyValue获取样式,后者使用getAttribute获取样式;

c.getPropertyValue中传入的变量不支持驼峰标示,多单词的css属性名只能以“-”连接,比如getPropertyValue(“background-color”)合法,而getPropertyValue(“backgroundColor”)非法;IE有时候传入“-”连接符变量可以获取正确结果,有时候传入驼峰标识变量能获取正确结果,IE11下测试如下图

getComputedStyle与currentStyle[通俗易懂]
getComputedStyle与currentStyle[通俗易懂]

d.在获取width、height等表示空间大小的样式时,getComputedStyle一般都返回具体的像素大小,比如“200px”,是一个绝对的大小;而currentStyle返回的有可能不是绝对值而是之前设置的相对值,比如“50%”等,以下为在IE11下对百度首页的测试结果

getComputedStyle与currentStyle[通俗易懂]
getComputedStyle与currentStyle[通俗易懂]

其实在大部分情况下,width、height等的绝对值对我们的用处更大,而且currentStyle也只是微软自家的属性,不是标准,所以在IE9+的浏览器下推荐使用getComputedStyle

6.兼容所有浏览器计算样式的代码

代码语言:javascript
复制
//将名称转换成驼峰标志的形式
	function toCamelCase(name){
		var result = "";
		var words = name.split("-");
		for(var i=0;i<words.length;i++){
			var word = words[i].toLowerCase();
			if(i !== 0){
				word = word[0].toUpperCase() + word.slice(1,word.length);
			}
			result += word;
		}
		return result;
	}

	//将变量名称转换成"-"连接符形式
	function toHyphen(name){
		var result = "";
		for(var i=0;i<name.length;i++){
			var c = name[i];
			if(i !== 0){
				if(c.match(/[A-Z]/g)){
					c = "-"+c.toLowerCase();
				}
			}
			result += c;
		}
		return result;
	}

	//通过currentStyle得到样式
	function _getStyleforIE(dom,styleName){
		var result = null;
		if(dom.currentStyle){
			styleName = toHyphen(styleName);
			result = dom.currentStyle.getAttribute(styleName);
			if(!result){
				styleName = toCamelCase(styleName);
				result = dom.currentStyle.getAttribute(styleName);
			}
		}
		return result;
	}

	//兼容所有浏览器的计算样式的方法
	function getElementComputedStyle(dom,styleName){
		if(!(dom instanceof HTMLElement)){
			return null;
		}
		if(typeof styleName !== "string"){
			return null;
		}
		else{
			styleName = styleName.replace(/\s/,"");
			if(styleName === ""){
				return null;
			}
		}

		var style = null;

		if(document.defaultView){					
			var domStyles = document.defaultView.getComputedStyle(dom,null);
			styleName = toHyphen(styleName);
			style = domStyles.getPropertyValue(styleName);
			if(!style){
				if(dom.currentStyle){
					style = _getStyleforIE(dom,styleName);
				}
			}
		}
		else if(dom.currentStyle){
			style = _getStyleforIE(dom,styleName);
		}

		return style;
	}

在使用时调用getElementComputedStyle方法即可。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/158980.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年7月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档