【发布时间】:2016-03-29 13:06:50
【问题描述】:
有没有办法使用 Postcss API 将选择器添加到现有规则中?
myRule.addSelector(".newSelector") 之类的东西?
目前我必须这样做:
myRule.selector = myRule.selector ? myRule.selector + ", .newSelector" : ".newSelector";
【问题讨论】:
标签: postcss
有没有办法使用 Postcss API 将选择器添加到现有规则中?
myRule.addSelector(".newSelector") 之类的东西?
目前我必须这样做:
myRule.selector = myRule.selector ? myRule.selector + ", .newSelector" : ".newSelector";
【问题讨论】:
标签: postcss
您可以使用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。