2010-11-13 78 views
5

是否有可能使用JavaScript获取对象的所有样式?喜欢的东西:JavaScript获取样式

 

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? 

 
+0

我只是不明白这一点得到元素的当前CSS样式。 'main.js'应该做些什么? – Harmen 2010-11-13 14:06:19

+0

你的意思是自定义CSS定义的所有样式? – 2010-11-13 14:08:17

回答

15

你在说什么被称为计算样式,看看这些文章对如何获得它:

F ROM中的最后一篇文章,这里是一个函数:

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"); 
1

您可以使用:

var ob = document.getElementById("myLayer"); 
var pos = ob.style.position; 

每个CSS属性都有自己的对象模型。通常这些包含' - '的css属性是用java模型编写的。

例如:

//getting background-color property 
var ob = document.getElementById("myLayer"); 
var color = ob.style.backgroundColor; 

如果你想获得那些为对象定义的所有CSS属性,你将不得不逐个一一列举了,因为即使你没有设置该属性你的样式表中,一个对象将使用默认值。

+1

“Java模型”是什么意思?你的意思是骆驼案件? – 2010-11-13 14:16:36

+0

是的,我确实,对不起。 – 2010-11-13 14:17:14

+0

如果您仔细阅读该问题,您会发现OP不*使用内联CSS。 – PleaseStand 2010-11-13 14:21:48

2

填充工具使用JavaScript ...访问link更多信息

/** 
* @desc : polyfill for getting the current CSS style of the element 
* @param : elem - The Element for which to get the computed style. 
* @param : prop - The Property for which to get the value 
* @returns : The returned style value of the element 
**/ 
var getCurrentStyle = function (ele, prop) { 

var currStyle; 
if (!window.getComputedStyle) { 
    currStyle = ele.currentStyle[prop]; 
} else { 
    currStyle = window.getComputedStyle(ele).getPropertyValue(prop); 
} 

return currStyle; 
} 


/** How to use **/ 
var element = document.getElementById("myElement"); 
getCurrentStyle(element, "width"); // returns the width value