本文介绍了JavaScript获取样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用JavaScript获取对象的所有样式?像:
Is it possible to get ALL of the styles for an object using JavaScript? Something like:
main.css
-------
#myLayer {
position: absolute;
width: 200px;
height: 100px;
color: #0000ff;
}
main.js
-------
var ob = document.getElementById("myLayer");
var pos = ob.(getPosition);
// Pos should equal "absolute" but
// ob.style.position would equal null
// any way to get absolute?
推荐答案
关于所谓的计算方式,请查看有关如何获取这些文章:
You are talking about what is known as Computed Style, check out these article on how to get it:
- Get Styles on QuirksMode
- Get Computed Style
- Get the rendered style of an element
最后一篇文章,这里是一个函数:
From the last article, here is a function:
function getStyle(oElm, strCssRule){
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
如何使用它:
CSS:
/* Element CSS*/
div#container{
font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;
}
JS:
var elementFontSize = getStyle(document.getElementById("container"), "font-size");
这篇关于JavaScript获取样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!