您的位置:首页 > Web前端 > CSS

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

2015-08-22 15:23 716 查看

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

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

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

<style type="text/css">
.test1{
background: purple;
}
.test2{
background: pink;
}
</style>
</head>
<body>
<div class='test1'  onclick="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'  onclick="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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: