這是不是有用如你所想,你必須記住繼承和順序,以及直接應用於元素的樣式。但是你可以通過自己的選擇和大多數其他瀏覽器,因爲再返回所有的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