2014-10-17 125 views
2

我想找到某個div內的所有類和ID!和這些CSS屬性!如何查找某個div內的所有css類及其css屬性?

例子:

<div class="demo"> 
<div class="new_class"> 
<p id="para">This is Demo Paragraph</p> 
<a style="background:#ccc">HyperLink</a> 

</div> 
</div> 

<style> 
.demo{ 

height:100px; width:100px; background:#FF0; 

} 
.new_class{height:40px; width:40px; background:#999;} 
#para{color:#E1E1E1;} 


</style> 

現在的問題是:我想找到這些演示類內部使用的所有class和id!和他們的css值(現在應用哪種風格)。 我想找到如下結果:

<style> 
.demo{ 

height:100px; width:100px; background:#FF0; 

} 
.new_class{height:40px; width:40px; background:#999;} 
#para{color:#E1E1E1;} 
a{background:#ccc;} 

</style> 
+4

到目前爲止你做了什麼嘗試? – 2014-10-17 05:06:40

+0

使用$(「。demo」)。children(),然後遍歷所有來檢索個人ID,類和樣式屬性。但是,所有的輸出結果都是使用javascript,而不是您期望的樣式標籤。此外,您將無法區分內聯樣式和其他樣式。 – 2014-10-17 05:07:02

回答

2

要查找所有現有id,嘗試:

var ids = []; 
$(".demo *").each(function(){ this.id && ids.push(this.id); }); 
console.log(ids); 

做同樣的事情class或其他任何東西。

但是,要獲得您的預期輸出,您必須首先獲取每個元素的已定義CSS樣式。哪一個應該包括在內?默認情況下,p獲得邊距和填充。你也包括這些嗎?您還需要深入研究所有的CSS聲明,以便找到應用的樣式,這幾乎是不可能的。

例如,

<div class="yellow"></div> 
<style> 
    div.yellow:not(.blue){ 
     background: yellow; 
    } 
</style> 

你如何獲得的<div>標籤的背景是什麼? .style.background? Nah,它返回""。那麼現在你將不得不通過document.styleSheets進入CSS聲明來查看哪一個應用了。你甚至可以檢查規則div.yellow:not(.blue)是否與你的元素匹配?祝你好運。 (可能有這樣的庫,或者你甚至可以利用jQuery的內部選擇器引擎.is,雖然它不會像CSS一樣)另一件你可以做的事情是嘗試getComputedStyle。它爲您提供每一個計算出來的樣式,甚至在您的聲明中都沒有。所以你想要做什麼是不可能做的。 (我什至不知道你在做什麼這樣的事情。)

3

OP,不知道你的目的是什麼,但一般來說,這可能是有用的。我有一個項目,我需要從一個站點嵌入一個花哨的模板到另一個站點的頁面上,這個頁面有一個截然不同的,相互衝突的樣式表。我使用了類似於以下的一些代碼,通過document.styleSheets獲取原始內容中的每個應用樣式,然後將它們全部重新應用爲內聯樣式,因此我可以將它放在「父」網站上,而不會造成樣式表衝突。

Fiddle

JS

var selector,rule; 
var result=[]; 
    var sheets = document.styleSheets; 
    for (var i in sheets) { 
     //rules or cssRules, depending on the browser 
     var rules = sheets[i].rules || sheets[i].cssRules; 
     //iterate over every css rule in the document 
     for (var r in rules) 
     { 
      selector=rules[r].selectorText; 
      rule=rules[r].cssText; 
      //select demo itself, as well as all of its children 
      $('.demo, .demo *').each(function() { 
       //console.log($(this),selector); 
       //for each element, see if it matches the current rule. add if it does 
       if ($(this).is(selector)) 
       { 
        result.push(rule);     
       } 
      }); 
     } 
    } 
console.log(result); 
//result[0] .demo { height: 100px; width: 100px; background: none repeat scroll 0% 0% rgb(255, 255, 0); } 
//result[1] .new_class { height: 40px; width: 40px; background: none repeat scroll 0% 0% rgb(153, 153, 153); } 
//result[2] #para { color: rgb(225, 225, 225); } 

當然,你將不得不調整這對你自己做的事情一樣,除去如果你將其應用到時會出現重複的樣式一個更大的HTML塊,並且用於處理內聯樣式(這不會嘗試執行,但您可以從style屬性獲取它們並在那裏工作...)以及可能的計算樣式,您可以通過它getComputedStyle,如@ Derek的答案所示。但這應該讓你開始。