获取对象在内存中计算后的样式

获取对象在内存中计算后的样式

下面的例子显示obj.style只能取得”内敛style”的值

对于<style></style>中的css属性值,则无能为力


<style type="text/css">
	.test1{
		background: purple;
	}
	.test2{
		background: pink;
	}
</style>
</head>
    <body>
    	<div class='test1'  οnclick="ch()" style="width:300px;height:300px;border-bottom:1px solid red;">
    		点击DIV,使其背景色红绿交替
    	</div>
    </body>
    <script type="text/javascript">
	    function ch(){
	    	var div=document.getElementsByTagName('div')[0];
    		if(div.className.indexOf("test1")>=0)
    		{
    			div.className="test2";
    		}
    		else
    		{
    			div.className="test1";
    		}

    		//var obj=document.getElementsByClassName('test1');

    		// var a=obj.style.width;
    		// var b=obj.style.height;
    		// var c=obj.style.borderBottomWidth;

    		div.style.width=parseInt(div.style.width)+5+'px';
    		div.style.height=parseInt(div.style.height)+5+'px';
    		div.style.borderBottomWidth=parseInt(div.style.borderBottomWidth)+10+'px';
	    }
    		
    </script>

我们可以用obj.currentStyle (ie内核) 和window.getComputedStyle(一般浏览器内核)来获取.

 

注意:只有IE和Opera支持使用currentStyle获取HTMLElement的计算后的样式,其他浏览器中不支持

标准浏览器中使用getComputedStyle,IE9以上也支持getComputedStyle.

 

window.getComputedStyle(obj,伪元素)

参数说明

第一个参数为要获取计算后的样式的目标元素

第二个参数为期望的伪元素,如:’after’,’frist-letter’等,一般为null

 

考虑兼容性,封装函数

function getStyle:function(el,attr){

         returnel.currentStyle?el.currentStyle[attr]:getComputedStyle(el,null)[attr];

}

注意:这2个方法,获取的对象是只读的,要改样式,还得靠obj.style

eg:

<style type="text/css">
	div {
		width: 300px;
		height: 300px;
		border-bottom: 1px solid red;

	}
	.test1{
		background: purple;
	}
	.test2{
		background: pink;
	}
</style>
</head>
    <body>
    	<div class='test1'  οnclick="ch()" >
    		点击DIV,使其背景色红绿交替
    	</div>
    </body>
    <script type="text/javascript">
    	function getStyle(el,attr){
		return el.currentStyle ? el.currentStyle[attr]:getComputedStyle(el,null)[attr];
	}
	    function ch(){
	    	var div=document.getElementsByTagName('div')[0];
    		if(div.className.indexOf("test1")>=0)
    		{
    			div.className="test2";
    		}
    		else
    		{
    			div.className="test1";
    		}

    		//alert(getStyle(div ,'width'));
    		//return;

    		div.style.width=parseInt(getStyle(div ,'width'))+5+'px';
    		div.style.height=parseInt(getStyle(div ,'height'))+5+'px';
    		div.style.borderBottomWidth=parseInt(getStyle(div ,'borderBottomWidth'))+10+'px';
	    }
    		
    </script>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值