我希望在 if 语句中定义变量可以在 Sass 中工作,但不幸的是我收到错误消息,说变量未定义。这是我尝试过的:
@for !i from 1 through 9
!foo = #000
@if !i == 1
!bg_color = #009832
@if !i == 2
!bg_color = #195889
...
#bar#{!i}
color: #{!foo}
background-color: #{!bg_color}
使用此代码,我会收到以下错误:
Undefined variable: "!bg_color".
最佳答案
Sass 变量仅对声明它们的缩进级别以及嵌套在其下的缩进级别可见。所以你只需要在你的 for 循环之外声明 !bg_color :
!bg_color = #FFF
@for !i from 1 through 9
!foo = #000
@if !i == 1
!bg_color = #009832
@if !i == 2
!bg_color = #195889
#bar#{!i}
color: #{!foo}
background-color: #{!bg_color}
你会得到以下 css:
#bar1 {
color: black;
background-color: #009832; }
#bar2 {
color: black;
background-color: #195889; }
#bar3 {
color: black;
background-color: #195889; }
#bar4 {
color: black;
background-color: #195889; }
#bar5 {
color: black;
background-color: #195889; }
#bar6 {
color: black;
background-color: #195889; }
#bar7 {
color: black;
background-color: #195889; }
#bar8 {
color: black;
background-color: #195889; }
#bar9 {
color: black;
background-color: #195889; }
关于sass - 在 if 语句中声明的变量导致 "undefined variable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1510803/