这是不是有用如你所想,你必须记住继承和顺序,以及直接应用于元素的样式。但是你可以通过自己的选择和大多数其他浏览器,因为再返回所有的CSS规则,在IE7 +:
function getRules(rx){
var A= [], tem, R= this.cssRules || this.rules, L= R.length;
if(typeof rx== 'string') rx= new RegExp('\\b'+rx+'(,|$)', 'i');
while(L){
tem= R[--L] || '';
if(tem.selectorText && rx.test(tem.selectorText)){
A[A.length]= tem.style.cssText || '';
}
}
return A;
}
function getAllRules(sel){
var A= [], S= document.styleSheets, L= S.length, tem;
while(L){
tem= getRules.call(S[--L], sel);
while(tem.length){
A[A.length]= tem.shift();
}
}
A= A.join(';').split(/;+\s*/);
return A;
}
getAllRules('body')// element selector
getAllRules('#p_opts')//id selector
getAllRules('.emhooCss')// class selector
getAllRules('#ul_tree h4 span')// descendent selector
getAllRules(/\b(body|div|p)\b/i)//rx for multiple selectors
使对象涉及分裂阵列
function Cssruler(sel){
var R= getAllRules(sel), L= R.length, tem;
while(L){
tem= R[L--] || '';
tem= tem.split(/\s*\:\s*/);
if(tem.length== 2) this[tem[0]]= tem[1];
}
this.selector= sel;
}
VAR的碎片R = new Cssruler('body')
R contains an object like this:
{
background: 'none repeat scroll 0% 0% rgb(250, 250, 250)',
background-color: 'black',
background-image: 'url("starynte.gif")',
color: 'black',
left: '0pt',
margin: '0pt',
padding-top: '2.5em',
right: '0pt',
selector: 'body',
width: 'auto'
}
为什么要这样做?如果你想知道这一点,那么只需检查萤火虫中的元素。 – CarneyCode 2011-02-27 05:29:08
如果您正在寻找通过样式表设置的值,那么没有快速修复(我知道)来获取这些样式。但是,这里有一个代码片段,它提取了特定元素的计算样式(Firebug使用类似这样的东西)。 http://www.quirksmode.org/dom/getstyles.html#link7 – 2011-02-27 05:30:19