在js中获取css样式方法及不同浏览器兼容问题

在js中获取css样式的方法

一、使用currentStyle

使用方法为 currentStyle . 样式名
例如

alert(box.currentStyle.height); 

但是该方法有一个缺陷只能在IE中使用

二、使用getComputedStyle

使用方法为 getComputedStyle( , )
getComputedStyle( , )里面有两个值第一个为所获取的元素,第二个一般为空

var obj = document.getElementById("obj");
getComputedStyle(obj,null);

获取其中具体样式方法

var obj = getComputedStyle(obj,null)
alert(obj.width);

但是这种方法也有局限它不支持IE8及以下的浏览器
因此可以采用一个更为兼容的方法

三、创建一个getStyle()函数

function getStyle(obj,name){
	if(window.getComputedStyle){  //判断浏览器
		return getComputedStyle(obj,null)[name];
	}
	else{
		return box.currentStyle[name];
	}
}

还有一种写法与上面的效果一样 但是逼格更高

function getStyle(obj,name){
	return window.getComputedStyle?getComputedStyle(box,null)[name]:box.currentStyle[name];
}

下面是整体源代码,了解一下HTML和css部分和整体的效果

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#box{
				width: auto;
				height: 100px;
				background-color: aqua;
			}
		</style>
		<script type="text/javascript">
			window.onload = function(){
				var box = document.getElementById("box");
				var btn = document.getElementById("btn");
				btn.onclick = function(){
					
					// alert(box.currentStyle.height);    //仅限IE
						// var obj = getComputedStyle(box,null);
						// alert(obj.width);//不支持IE8及以下的浏览器
						alert(getStyle(box,"width"));
				}
				function getStyle(obj,name){
					if(window.getComputedStyle){
						return getComputedStyle(obj,null)[name];
					}
					else{
						return box.currentStyle[name];
					}
				}
				function getStyle(obj,name){
					return window.getComputedStyle?getComputedStyle(box,null)[name]:box.currentStyle[name];
				}
			}
		</script>
	</head>
	<body>
		<div id="box"></div>
		<button type="button" id="btn">点击</button>
	</body>
</html>

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值