Skip to content

获取元素的具体样式信息 #38

Open

Description

@Yangxiaqing

获取元素的某一个具体的样式属性

元素.style.属性名

需要我们把元素的样式都写在行内样式上才可以(写在样式表中是不管用的)

console.log(box.style.height);//""
console.log(box.style.width);//"200px"

在真实项目中,这种方式不常用,因为我们不能为了获取值而把所有的样式都写在行内(无法实现CSS和HTML的分离)

使用window.getComputedStyle这个方法获取所有经过浏览器计算过的样式

所有经过浏览器计算过的样式——只要当前元素标签可以在页面中呈现出来,那么它的所有的样式都是经过浏览器计算过的(渲染过的),哪怕有些样式你没有写,我们也可以获取到:
window.getComputedStyle(当前要操作的元素对象,当前元素的伪类[一般我们不用伪类写null])
获取的结果是CSSStyleDeclaration这个类的一个实例:包含了当前元素所以样式属性和值

console.log(window.getComputedStyle);//function getComputedStyle() { [native code] }
console.log(window.getComputedStyle(box, null));

方法虽好,但是在IE6~8下不兼容

因为window下没有getComputedStyle这个属性,执行这个方法会报错

console.log(window.getComputedStyle);//undefined

在IE6~8下,我们可以使用currentStyle来获取所以经过浏览器计算过的样式:

console.dir(box.currentStyle.height);

getCss——获取当前元素所有经过浏览器计算过的样式中的[attr]对应的值

  • 使用try,catch来处理兼容(只有在不得已的情况下才使用它)
    前提:必须保证try中的代码在不兼容浏览器中执行的时候报错,这样的话我们才可以用catch捕获到异常信息,进行其他的处理
    不管当前是什么浏览器,都需要先把try中的代码执行一遍,如果当前是IE7,window.getComputedStyle本身是不兼容的,但是我们也要先把它执行一遍,报错了,再把curEle.currentStyle执行一遍(消耗性能)
//curEle:[object]当前要操作的元素对象
//attr:[string]我们要获取的样式属性的名称
function getCss(curEle, attr) {
	var val = null;
	try {
		val = window.getComputedStyle(curEle, null)[attr];
	} catch(e) {
		val = curEle.currentStyle[attr];
	}
	return val;
}
console.log(getCss(box, "height"));
  • 判断当前浏览器中是否存在这个属性或者方法,存在就兼容,不存在就不兼容
function getCss(curEle, attr) {
	var val = null;
	if ("getComputedStyle" in window) {
		//如果返回的是true,说明window下有getComputedStyle这个属性,代表兼容
		val = window.getComputedStyle(curEle, null)[attr];
	} else{
		//代表不兼容
		val = curEle.currentStyle[attr];
	}
	return val;
}
console.log(getCss(box, "height"));
function getCss(curEle, attr) {
	var val = null;
	if (window.getComputedStyle) {
		//首先获取属性值,兼容返回的是一个函数,转换为布尔是true,不兼容返回结果是undefined,准换为布尔是false
		val = window.getComputedStyle(curEle, null)[attr];
	} else{
		val = curEle.currentStyle[attr];
	}
	return val;
}
console.log(getCss(box, "height"));
function getCss(curEle, attr) {
	var val = null;
	if (typeof window.getComputedStyle === "function") {
		val = window.getComputedStyle(curEle, null)[attr];
	} else{
		val = curEle.currentStyle[attr];
	}
	return val;
}
console.log(getCss(box, "height"));
  • 通过检测浏览器版本和类型来处理兼容
    window.navigator.userAgent
    谷歌:"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"
    。。。
    扩展题:
    自己写一个方法,可以检测当前是什么浏览器,也可以获取到浏览器的版本号。。。
    获取到当前浏览器是IE6~8:
/MSIE (6|7|8)/.test(navigator.userAgent)
function getCss(curEle, attr) {
	var val = null;
	if (/MSIE (6|7|8)/.test(navigator.userAgent)) {
		val = curEle.currentStyle[attr];
	} else{
		val = window.getComputedStyle(curEle, null)[attr];
	}
	return val;
}

补充知识:

写CSS的时候第一步初始化默认样式,避免浏览器之间的差异,不仅如此,而且写的默认样式对于JS以后获取到的结果统一也是有帮助的。

实战练习:

	<style>
		*{
			margin: 0;
			padding: 0;
			font-size: 14px;
		}
		#box{
			width: 200px;
			height: 200px;
			border: 10px solid #000;
			margin: 100px auto;
			padding: 30px;
			line-height: 30px;
                        opacity: 0.1;
			filter: alpha(opacity = 10);
		}
	</style>
<div id="box">
	本文为作者张箬涵原创,非授权请勿转载,否则维权 山东,我的故乡,齐鲁大地,既有半岛海洋文化,又有齐鲁文化源远流长,孔孟等各路圣贤诞生于此。全国经济GDP常年第三,山东人的...
</div>
<script>
	var box = document.getElementById('box');
</script>
	function getCss(curEle, attr) {
		var val = null;
		if ("getComputedStyle" in window) {
			val = window.getComputedStyle(curEle, null)[attr];
		} else{
			val = curEle.currentStyle[attr];
		}
		return parseFloat(val);
		//这样写肯定不行,对于某些样式属性的值是不能去单位的,例如:float、margin、position、padding、border这些复合值、background。。。
	}
	console.log(getCss(box, "width"));
	console.log(getCss(box, "float"));
//第一次升级:把获取到的样式值"单位去掉"
//只有符合"数字+单位/数字"才能使用parseFloat
function getCss(curEle, attr) {
	var val = null,reg = null;
	if ("getComputedStyle" in window) {
		val = window.getComputedStyle(curEle, null)[attr];
	} else{
		val = curEle.currentStyle[attr];
	}
	reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i;
	return reg.test(val) ? parseFloat(val) : val;
}
console.log(getCss(box, "width"));//200
console.log(getCss(box, "float"));//none
console.log(getCss(box, "border"));//10px solid rgb(0, 0, 0)
	//第二次升级:有些样式属性在不同浏览器中是不兼容的,例如:opacity
	function getCss(curEle, attr) {
		var val = null,reg = null;
		if ("getComputedStyle" in window) {
			val = window.getComputedStyle(curEle, null)[attr];
		} else{//IE6~8
			//如果传递进来的结果是opacity,说明我想获取到的是透明度,但是在IE6~8下获取透明度需要使用filter
			if (attr === "opacity") {
				val = curEle.currentStyle["filter"];
				//"alpha(opacity = 10)" 把获取到的结果进行剖析,获取里面的数字,让数字乘以100才和标准的浏览器保持一致
				reg = /^alpha\(opacity=(\d+(?:\.\d+)?)\)$/i;
				val = reg.test(val) ? reg.exec(val)[1]/100 : 1;
			}else{
				val = curEle.currentStyle[attr];
			}
		}
		reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i;
		return reg.test(val) ? parseFloat(val) : val;
	}
	console.log(getCss(box, "opacity"));

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions