2014-11-04 60 views
1

首先,對不起,我沒有在這裏放任何代碼,因爲我不知道該怎麼做。如何獲取包含特定顏色的CSS選擇器?

我需要的是獲得所有CSS選擇器(在一個CSS文件中)明確包含顏色...比方說#3C3C3C,舉個例子。

例:讀一個CSS文件

.first-selector div 
{ 
color: #3C3C3C; 
} 
.second-selector span 
{ 
background-color: #3C3C3C; 
} 
.thrid-selector 
{ 
border: 1px solid #3C3C3C; 
} 
.fourth-selector .nothing 
{ 
color: #00000; 
} 

預期結果 - 提取成數組(唯一包含特定顏色風格)

array[0]['selector'] == ".first-selector div" 
array[0]['style'] == "color" 

array[1]['selector'] == ".second-selector span" 
array[1]['style'] == "background-color" 

array[2]['selector'] == ".thrid-selector" 
array[2]['style'] == "border" 

應該是什麼邏輯搜索具有特定顏色的選擇器並將其放入數組中?

注意這將在服務器端進行處理。

感謝

+0

,沒有PHP或Java參與。 – 2014-11-04 11:42:57

+0

以及「java」如何與網頁建設相關? – 2014-11-04 11:43:31

+0

當你說Java時,你碰巧指的是jQuery? – user2209644 2014-11-04 11:44:00

回答

0

使用文件的概念,只寫在JS邏輯讀取文件的內容,然後使用一些正則表達式邏輯或任何其他邏輯一樣通過傳遞delimtre值分割的內容。事實上,這不是正確的做法,只是一個想法

+0

「一個想法」不會被視爲答案。事實上,任何人都可以想出解決方案,但是你必須意識到這一點。 ;) – 2014-11-04 11:54:00

+0

嗯...是的,我們ryt。但是用這種方法我們可以得到預期的輸出。但我剛纔提到的是Idea,因爲要求的人可能會或可能不會喜歡這種方法。 :( – 2014-11-04 12:00:27

+0

期望的OP **不**接受你的答案。 – 2014-11-04 12:02:25

0

JavaScript將讓你訪問應用到文檔的所有樣式。檢查每一個,看它是否包含顏色。

CSS

<style> 
    .first-selector div 
    { 
     color: #3C3C3C; 
    } 
    .second-selector span 
    { 
     background-color: #3C3C3C; 
    } 
    .third-selector 
    { 
     border: 1px solid #3C3C3C; 
    } 
    .fourth-selector .nothing 
    { 
     color: red; 
    } 
</style> 

JS:

<script> 
    function getColorRules(color) 
    { 
//convert hex to rgb, since hex color styles are internally stored as rgb 

     if (/[#]{0,1}[0-9A-F]{6}/.test(color)) 
     { 
      color = color.replace('#', ''); 
      var r = parseInt(color.substr(0, 2), 16); 
      var g = parseInt(color.substr(2, 2), 16); 
      var b = parseInt(color.substr(4, 2), 16); 
      color = "rgb(" + r + ", " + g + ", " + b + ")"; 
     } 


     var returnArray = []; 
     //grab all stylesheets 
     var sheets = document.styleSheets; 
     for (var i in sheets) { 
      //to work in FF or chrome 
      var rules = sheets[i].rules || sheets[i].cssRules; 
      for (var r in rules) 
      { 
       //console.log(rules[r]); 

       if (rules[r].cssText !== undefined) { //ignore empty or non css properties 
        if (rules[r].cssText.indexOf(color) > -1) //if the color is found in the style rule 
        { //add it to an array 
         var style = { 
          selector: rules[r].selectorText, 
          style: rules[r].style.cssText.split(":")[0] 
         }; 
         returnArray.push(style); 
        } 
       } 
      } 
     } 
     return returnArray; 
    } 
    console.log(getColorRules("#3C3C3C")); 
//[{ selector=".first-selector div", style="color"}, { selector=".second-selector span", style="background-color"}, { selector=".third-selector", style="border"}] 
    console.log(getColorRules("red")); 
// [{ selector=".fourth-selector .nothing", style="color"}] 
</script> 
如果你說 「搞定」