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

javascript 获取元素的真实,最终的css样式

2012-09-20 16:46 696 查看
elem.style.xxx只能获取内联的css属性,对<head>内的或link外部样式的无能为力。

<style>
h1{
font-size:1.6em;
color:red;
}
</style>

</head>

<body>
<h1id="title">helloworld</h1>
<p>thisisatesttxt</p>

<script>
varx=document.getElementById("title");
document.write(x.style.color);
</script>


其实

x.style.color="";
所以看不到样式信息.
AfunctionforfindingthecomputedstylevalueofanelementisshowninListing7-1


//Getastyleproperty(name)ofaspecificelement(elem)
functiongetStyle(elem,name){
//Ifthepropertyexistsinstyle[],thenit'sbeenset
//recently(andiscurrent)
if(elem.style[name])
returnelem.style[name];
//Otherwise,trytouseIE'smethod

elseif(elem.currentStyle)
returnelem.currentStyle[name];
//OrtheW3C'smethod,ifitexists

elseif(document.defaultView&&document.defaultView.getComputedStyle){
//Itusesthetraditional'text-align'styleofrulewriting,
//insteadoftextAlign
name=name.replace(/([A-Z])/g,"-$1");
name=name.toLowerCase();
//Getthestyleobjectandgetthevalueoftheproperty(ifitexists)
vars=document.defaultView.getComputedStyle(elem,"");
returns&&s.getPropertyValue(name);
//Otherwise,we'reusingsomeotherbrowser
}else
returnnull;
}


w3c办法,它使用的是通用的text-align而非textAlign;所以先要把属性名替换。

注意;几乎任何属性都会返回表示元素样式的字符串而非数值(比如是100px而非100);

<html>
<head>
<style>p{height:100px;}</style>
<script>
window.onload=function(){
//Locatetheparagraphtochecktheheightof
varp=document.getElementsByTagName(“p”)[0];

//Checktheheightthetraditionalway
alert(p.style.height+“shouldbenull”);

//Checkthecomputedvalueoftheheight
alert(getStyle(p,“height”)+“shouldbe100px”);
};
</script>
</head>
<body>
<p>Ishouldbe100pixelstall.</p>
</body>
</html>


上面展示了如何获取一个dom元素的css属性的最终真实值。需要注意的是:这个函数忽略的其他的计量单位(如百分比)。所以这个方法并不完美,但已经是一个很好的开端。

chrome下height:x%;

不过是x是什么,都是18。

Ie的currentStyle对象代表了在全局样式表、内嵌样式和HTML标签属性中指定的对象格式和样式。http://msdn.microsoft.com/en-us/library/ie/ms535231(v=vs.85).aspx

W3c:
document.defaultView
browsersreturnsthewindowobjectassociatedwiththedocumentor[code]null
ifnoneavailable
[/code]
varwin=document.defaultView;

[code]getComputedStyle()
givesthefinalusedvaluesofalltheCSSpropertiesofanelement.[/code]
varstyle=window.getComputedStyle(element[,pseudoElt]);
Thereturned[code]style
isa
CSSStyleDeclaration
object.
pseudoEltOptional
Astringspecifyingthepseudo-elementtomatch.Mustbe
null
(ornotspecified)forregularelements.
通常的元素必须为null。

[/code]
[code]CSSStyleDeclaration
方法[/code]
getPropertyValue(propertyName)
removeProperty(propertyName)

参考:https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: