js获取css样式

css样式分为以下三种:

1、内联样式(在HTML元素的内部,又称行内样式)。

2、内部样式(位于<head>标签内部)。

3、外部样式(通过link标签引入)。

通过javascript获取元素内联样式可以直接通过elementobj.style.prop即可获取。

如果要获取内部样式或外部样式上面那种方法就失效了,做法如下:

DOM标准里有个全局方法getComputedStyle,可以获取到当前对象样式规则信息,如:getComputedStyle(obj,null).backgroundColor,就能获取到对象的左内边距。但是IE不支持此方法,它有自己的一个实现方式,那就是currentStyle,不同于全局方法getComputedStyle,它是作为DOM元素属性存在的,如:obj.currentStyle.backgroundColor,在IE中就获取到对象的左内边距了,兼容性的写法如下:

return window.getComputedStyle?window.getComputedStyle(obj,null).backgroundColor :obj.currentStyle.backgroundColor;

按例代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>body换肤</title>
		<style type="text/css">
			*{margin: 0px;padding: 0px;}
			ul{list-style: none;}
			.myul1 li{display: inline-block;width: 30px;height: 20px;font-size: 0px;cursor: pointer;}
			.myul1 li:first-child{background-color: #f00;}
			.myul1 li:nth-child(2){background-color: #0f0;}
			.myul1 li:nth-child(3){background-color: #00f;}
		</style>
	</head>
	<body>
		<ul class="myul1" id="myul1">
			<li>红色</li>
			<li>绿色</li>
			<li>蓝色</li>
		</ul>
		<script type="text/javascript">
			var ali=document.getElementById('myul1').getElementsByTagName('li');
			for(var i=0;i<ali.length;i++){
				ali[i].onclick=function(){
					// window.getComputedStyle非IE
					//currentStyle   IE
					// return window.getComputedStyle?window.getComputedStyle(obj,null).backgroundColor :obj.currentStyle.backgroundColor;
					var color=window.getComputedStyle?window.getComputedStyle(this,null).backgroundColor:this.currentStyle.backgroundColor;
					document.getElementsByTagName('body')[0].style.background=color;
				}
			}
		</script>
	</body>
</html>

对样式进行封装一下:

var ali=document.getElementById('myul1').getElementsByTagName('li');
			for(var i=0;i<ali.length;i++){
				ali[i].onclick=function(){
					var color=getStyle(this,'backgroundColor');
					document.getElementsByTagName('body')[0].style.background=color;
				}
			}
			function getStyle(obj,attr){
				//非IE浏览器
				if(window.getComputedStyle){
					return window.getComputedStyle(obj,null)[attr];
				}else if(obj.currentStyle){//IE浏览器
					return obj.currentStyle[attr];
				}
				return null;
			}

基于IE浏览器的非行内获取法:使用 obj.currentStyle["attr"];基于非IE浏览器,如火狐谷歌等非行内获取法:使用window.getComputedStyle(obj)["attr"]

切记:非行内样式获取法,只能获取不能设置,一般情况下,通过js设置的样式都是内联样式。

.与[]的区别

(1).与[]均可以用于获取对象属性,但是写法存差异。.后面直接跟属性,[]中的属性需要以字符串或变量的形式传入。

设置obj的背景为#f00。

.的书写方式:

obj.style.backgroundColor='#f00';

[]的书写方式:

obj.style['backgroundColor']='#f00';

(2).不能传入变量,而[]可以传入变量
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值