【问题标题】:Can Stylus interpolate for a property value rather than a property name?Stylus 可以插入属性值而不是属性名称吗?
【发布时间】:2021-09-24 09:56:26
【问题描述】:

我正在尝试在 Stylus 中使用 Mixin 和插值来设置 .tag 的样式。我希望 Mixin 将 tagName 作为变量并将其传递给某些属性的值,以便为其他地方定义的值生成变量。

假设我有一个为不同的.tag 定义颜色变量的 Stylus 文件,例如color-TODO = red。然后,生成如下 CSS:

.tag-TODO
  color: red                // from color-TODO
  background: blue          // from color-TODO-background
  box-shadow: 0 0 4px green // from color-TODO-shadow

,我想用这样的 Mixin 制作另一个 Stylus 文件:

tag(tagName)
  .tag-{tagName}                                // for .tag-TODO
    color: color-{tagName}                      // for color-TODO
    background: color-{tagName}-background      // for color-TODO-background
    box-shadow: 0 0 4px color-{tagName}-shadow  // for color-TODO-shadow

tag(TODO)                                       // to generate the selector with the properties

这不起作用,大概是因为属性标识符之后的{} 被逐字解释,而不是作为 Mixin 变量进行插值。

我想知道是否有解决方法。有没有办法(在 Stylus 中)让 Mixin(或其他构造)生成不同的变量名,共享相同的字符串作为不同的属性值?

【问题讨论】:

    标签: css mixins stylus


    【解决方案1】:

    使用convert() 内置函数(参见https://stylus-lang.com/docs/bifs.html),您可以这样做:

    // your variables
    color-TODO = #000
    color-TODO-background = #666
    color-TODO-shadow = #f2f2f2
    
    // your mixin
    tag(tagName)
      .tag-{tagName}
        color: convert("color-" + tagName)
        background: convert("color-" + tagName + "-background")      // for color-TODO- background
        box-shadow: 0 0 4px convert("color-" + tagName + "-shadow")  // for color-TODO-shadow
    
    // execution
    tag(TODO)
    

    产生 css :

    .tag-TODO {
      color: #000;
      background: #666;
      box-shadow: 0 0 4px #f2f2f2;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-28
      • 2020-10-05
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多