【问题标题】:How to add a selector to an existing rule?如何将选择器添加到现有规则?
【发布时间】:2016-03-29 13:06:50
【问题描述】:

有没有办法使用 Postcss API 将选择器添加到现有规则中? myRule.addSelector(".newSelector") 之类的东西?

目前我必须这样做:

myRule.selector = myRule.selector ? myRule.selector + ", .newSelector" : ".newSelector";

【问题讨论】:

    标签: postcss


    【解决方案1】:

    您可以使用rule.selectors,这是一个带有getter 的属性,它返回一个选择器数组(从rule.selector 字符串生成)和一个setter,它采用一个选择器数组(并覆盖rule.selector 字符串)。

    var sels = myRule.selectors; //save the getter returned array so we can modify it with push.
    sels.push('.newSelector'); //push returns the new length not the array, that's why we had to save the array in sels.
    myRule.selectors = sels; //the setter will join the array elements and overwrite myRule.selector
    

    使用concat 的更短版本(因为concat 返回一个新数组)。

    myRule.selectors = myRule.selectors.concat('.newSelector');
    

    查看 PostCSS 源代码here

    【讨论】:

    • var sels = myRule.selectors 如果没有定义选择器,则返回错误TypeError: Cannot read property 'length' of undefined
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    • 2014-08-05
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多