我希望在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}
使用此代码,我会收到以下错误:
未定义变量:“!bg_color”。
答案 0 :(得分:11)
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; }