在 if 语句内声明的变量会导致“未定义的变量”

发布于 2024-08-06 00:59:04 字数 387 浏览 4 评论 0原文

我希望在 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”。

I was hoping that defining variables in an if statement would work in Sass but unfortunately I get errors saying that the variable isn't defined. Here is what I tried:

@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}

With this code, I would get the following error:

Undefined variable: "!bg_color".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无远思近则忧 2024-08-13 00:59:04

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 variables are only visible to the level of indentation at which they are declared and those nested underneath it. So you only need to declare !bg_color outside of your for loop:

!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}

And you'll get the following 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; }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文