如何在@media中获取选择器?

时间:2018-05-14 08:27:20

标签: java css css-parsing

我试图使用CSSParser解析css 例如,我有css:

 final String css = "@media screen and (color) { h1 { color: red } }";

我想得到这个部分:

{ h1 { color: red } }

但是当我使用mediaList

进行此操作时
    final CSSStyleSheet sheet = parse(css);
    final CSSRule cssRule = sheet.getCssRules().item(0);
    final MediaList mediaList = ((CSSMediaRuleImpl) cssRule).getMedia();

我只得到

输出:屏幕和(颜色)

也许有人遇到过这个问题?

2 个答案:

答案 0 :(得分:0)

我不是假装知道这是什么,但是 一个

({.*})

regexp可能有所帮助。

答案 1 :(得分:0)

如果有人需要回答:

@Test
public void testCSSParser2() throws IOException {
    String css = "@media only screen and (max-width: 600px) {body { background-color: lightblue } h1 { color: red } }";
    InputSource source = new InputSource(new StringReader(css));
    CSSOMParser parser = new CSSOMParser(new SACParserCSS3());
    CSSStyleSheet sheet = parser.parseStyleSheet(source, null, null);
    CSSRuleList rules = sheet.getCssRules();
    for (int x = 0; x < rules.getLength(); x++) {
        final CSSMediaRule mediaRule = ((CSSMediaRule) rules.item(x));
        CSSRuleList mediaRules = mediaRule.getCssRules();
        for (int y = 0; y < mediaRules.getLength(); y++) {
            final CSSRule rule = mediaRules.item(y);
            System.out.println(rule.getCssText());

        }
    }

}
相关问题