簡體   English   中英

如何將CSS選擇器解析和提取為字符串?

[英]How to parse and extract CSS selectors as strings?

將CSS選擇器提取為字符串的最簡單方法是什么?

鑒於此作為輸入:

#article{width:690px;overflow:hidden}
#article h2:first-child a{text-decoration:none}
#works .project p:last-child{margin-top:20px;font-size:13px}
#works .project img, #works .info img{width:680px;min-height:400px;border:1px dotted #ccc;margin-bottom:40px}

我如何獲得這樣的選擇器列表:

var selectors = ['#article','#article h2:first-child a','#works .project p:last-child','#works .project img']

定義“輸入。如果是在瀏覽器已解析的樣式表中,則可以使用DOM Level 2樣式 API提取樣式表中的CSS規則並查詢選擇器(盡管您可能需要用逗號分隔) 。

如果瀏覽器未解析它,但通過其他機制將其作為輸入提供,則您可以使用JSCSSP (JavaScript中的CSS解析器)來解析輸入。

這是我最終得到的解決方案:

  1. 用一些獨特的字符替換大括號,包括其內容。 正則表達式是從這里獲取的,帶有Java RegExp的CSS選擇器匹配
  2. 將列表拆分為那些唯一的字符。

只是想將其發布在此處進行記錄:

var css = "#article[type=x]{width:690px;overflow:hidden}#article h2:first-child a{text-decoration:none}#works .project p:last-child{margin-top:20px;font-size:13px}#works .project img, #works .info img{width:680px;min-height:400px;border:1px dotted #ccc;margin-bottom:40px}"
var found = css.replace(/{([^}]*)}/gm,"~~~").split("~~~");

document.write(found);

警告:Waporcode,我沒有測試過,但是我以前使用過類似的東西。

    document.styleSheets[0].cssRules[0].selectorText

那是您要找的東西嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM