【问题标题】:CSS, Stylus: conditional "else" is ignoredCSS,Stylus:有条件的“else”被忽略
【发布时间】:2021-11-06 10:40:47
【问题描述】:

我正在尝试在 Stylus 中创建 Mixins,这将允许我在一行中为 .theme-bright.theme-dark 定义元素的两种不同颜色。基于this,这是我目前的简化代码:

insert-Variable(Name, Value-bright, Value-dark)
  if theme-is-bright
    --color-{Name}: Value-bright
  else if theme-is-dark
    --color-{Name}: Value-dark

Variables()
  insert-Variable(Element1, black, white)
  insert-Variable(Element2, black, white)
  insert-Variable(Element3, black, white)

.theme-bright
  theme-is-dark = false
  theme-is-bright = true
  Variables()

.theme-dark
  theme-is-bright = false
  theme-is-dark = true
  Variables()

我希望它会产生这样的结果:

.theme-bright
  --color-Element1: black;
  --color-Element2: black;
  --color-Element3: black;
.theme-dark
  --color-Element1: white;
  --color-Element2: white;
  --color-Element3: white;

相反,我得到了这个:

.theme-bright
  --color-Element1: black;
  --color-Element2: black;
  --color-Element3: black;
.theme-dark
  --color-Element1: black;
  --color-Element2: black;
  --color-Element3: black;

--color-{Name}: Value-bright--color-{Name}: Value-dark 切换也会切换此意外结果:.theme-bright.theme-dark 下的值现在变为white。因此,显然,else if 下定义的任何值都会被if 下的值忽略或覆盖。

else if ... 更改为else 并不能解决此问题:它仍然只获取if 下定义的值。

我做错了什么?

【问题讨论】:

    标签: css conditional-statements stylus


    【解决方案1】:

    您正在尝试更新全局变量,但它在选择器的上下文中不起作用,因此只需将它们移出选择器即可:

    theme-is-dark = false
    theme-is-bright = true
    
    .theme-bright
      Variables()
    
    theme-is-bright = false
    theme-is-dark = true
    
    .theme-dark
      Variables()
    

    但是,从这段代码 sn-p 来看,您似乎通过使用 2 个不同的变量来传达相同的信息使其变得比需要的更难:theme-is-bright = true 应该等同于 theme-is-dark = false,但两者都不是insert-Variable mixin 中的语句将知道如何处理 theme-is-dark = false。您还需要一对 值来传达单点信息,而其他排列可能会产生意想不到的结果。我绝对建议将其缩减为单个变量。

    最后,为了清楚起见,我还建议将值添加到the mixin as an argument。这是一个编码风格推荐,因为它不会有效地改变你必须做的事情,但最终可能会更具可读性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-13
      • 1970-01-01
      • 2019-06-02
      • 2016-02-09
      • 2021-05-22
      • 1970-01-01
      • 2021-08-04
      • 2019-09-11
      相关资源
      最近更新 更多