不同的情况下读取当前元素的样式

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#btn1{
				background-color: burlywood;
			}
			#box1{
				border: 1px solid black;
				width: 100px;
				height: 100px;
				background-color: red;
			}
		</style>
		<script type="text/javascript">
			window.onload=function(){
				
				var box1=document.getElementById("box1");
				var btn1=document.getElementById("btn1");
				btn1.onclick=function(){
					alert(box1.style.backgroundColor);
					//用style只能能读取内联样式
				}
				
				var btn2=document.getElementById("btn2");
				btn2.onclick=function(){
					alert(box1.currentStyle.backgroundColor);

//用currentStyle读取元素当前显示的样式,如果当前元素不设置样式,则获取他的默认值
//currentStyle属性这个只有IE浏览器支持,其他浏览器不支持

				}
				
				
				
				var btn3=document.getElementById("btn3");				
				var box=getComputedStyle(box1,null );

//getComputedStyle方法可以获取元素当前的样式,该方法会返回一个对象,对象中封装了这个元素的样式
//该方法不支持IE8及以下的浏览器
//如果没有设置样式的宽度,则会设置他的实际宽度而不是默认宽度了

				btn3.onclick=function(){
					
					alert(box.backgroundColor);
					alert(typeof box.backgroundColor);
					alert(getStyle(box1,"backgroundColor"));
					//调用自己定义的getStyle()函数
					getStyle(box1,"backgroundColor");
				}

/*
* 通过currentStyle和getComputedStyle读取的样式都是只读的
* 不能修改,如果要修改,必须通过style属性
/
/

* 定义一个函数,用来获取元素当前的样式
* 参数:
* obj 要获取样式的元素
* name 要获取的样式名
*/
function getStyle(obj , name){

					/*getComputedStyle前面不加window就是一个变量
					  *在全局中没有这个变量,所以运行在IE浏览器时会报错
					  * 但是加了window就表示时window的一个属性
					  * 在IE浏览器中是没有这个属性的,只会返回undefied
					 * 
					 */
				if(window.getComputedStyle){
			    //正常浏览器的方法
				return getComputedStyle(obj,null)[name];
				}
				else{
				//IE8浏览器的方法
				return obj.currentStyle[name];//}
				}
			}
				
				
				
			}
			
		</script>
	</head>
	<body>
		<button id="btn1">点我一下获取内联样式</button>
		<button id="btn2">点我一下获取元素当前的样式</button>
		<button id="btn3">点我一下获取样式表中的样式样式</button>
		
		<button onclick="wo()">我是自己定义的函数</button>
		<br />
		<div id="box1" style="background-color: green;">123</div>
	</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值