JavaScript中如何用原生的js获取style样式

1. Element.style——只能获取内联样式

该方法只能获取到内联样式,而无法获取到<style></style>和<link href="">中的样式

例如:

<h1 onclick="getStyle(this)" style="color: red">测试</h1>
	function getStyle(obj){
		var color=obj.style.color;
		alert(color)
	}
但是当没有内联样式时,则无法获取到默认样式,
	function getStyle(obj){
		var backgroundColor=obj.style.backgroundColor;
		alert(backgroudColor);//空白
		obj.style.backgroundC='blue';
		alert(backgroundColor);//空白
	}

2. getComputedStyle()——获取最终样式,包括内联样式,不支持IE6-8

语法:window.getComputedStyle("元素", "伪类");

当不需要伪类是,第二个参数可以设置为null

	function getStyle(obj){
		var color=window.getComputedStyle(obj,null).backgroundColor
		alert(color);//rbga(0,0,0,0)
	}

也可以使用document.defaultView.getComputedStyle("元素", "伪类");


3. Element.currentStyle——适用于IE,可获取内联样式,返回最终样式

	function getStyle(obj){
		var backgroundColor=obj.currentStyle.backgroundColor
		alert(backgroundColor);//rbg(0,0,0)
	}


4. getPropertyValue()——不支持驼峰格式,不支持IE6-8

	function getStyle(obj){
		var backgroundColor=window.getComputedStyle(obj,null).getPropertyValue('background-color')
		alert(backgroundColor);//rbga(0,0,0,0)
	}

5. getAttribute——支持驼峰样式,与getPropertyValue()类似

为了兼容IE6-8,可以使用下面的方式获取样式

	function getStyle(obj){
		if(window.currentStyle){
			style=window.currentStyle(obj,null);
		}else{
			style=window.getComputedStyle(obj,null)
		}
		return style;
	}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值