使用SASS mixin创建多个背景

4

我正在尝试在Sass中创建一个mixin,以生成多个背景,问题是背景的数量是未知的,可能是3、4甚至5。这是我尝试并失败的代码:

@mixin multiBg($page: index, $sec: sec01,$from: 1, $to: 3, $type: jpg){
    $url: (); // i'm try to create a empty array first
    $newUrl: null; // and an empty variable
    @for $i from $from through $to {
        $newUrl: append($url, url(../img/#{$page}/#{$sec}_bg0#{$i}.#{$type})); // then append value to variable;
    }
    background: $newUrl;
}

#sec05 {
   @include multiBg(index,sec05);
}

当前输出:

background: url(../img/index/sec05_bg03.jpg);

预期输出:

background: url(../img/sec05_bg01.jpg),url(../img/sec05_bg02.jpg), url(../img/sec05_bg03.jpg);

由于我还在学习SASS,所以不知道该如何解决这个问题。请有经验的人指点一下。

2个回答

6

你已经在正确的轨道上了!但是你的语法和逻辑略有偏差。以下是我想到的:

@mixin multiBg($page: index, $sec: sec01, $from: 1, $to: 5, $type: jpg) {

  $url_list: ();

  @for $i from $from through $to {

    // I broke constructing the url and adding it to the set into two steps here.
    // We could do this all at once, but separating it can make it easier to read.

    // First, generate the url. 
    $url_string: url(../img/#{$page}/#{$sec}_bg0#{$i}.#{$type});

    // Then add it to the list (the 'comma' part is important)
    $url_list: append($url_list, $url_string, comma);  
  }

  // Done looping? Output the final list!
  background-image: $url_list;
}

这似乎可以返回您要查找的内容。这里是关于列表函数的官方文档 - 我总是忘记其中一两个,对您也可能有用。
另外,由于您提到您是sass新手 - 如果您还没有,请查看Sassmeister。它是一个方便的小沙盒,可以在sass中快速原型设计和尝试各种东西;类似于Codepen但更加专业化。这就是我用来实验这个问题的地方。

1
哦,哇,谢谢你的回答,它非常完美!!还要感谢你的建议 :) - VK Da NINJA

1

这是一个更清晰的答案,我相信。

@mixin image-resolve($image) {
  $images: ();

   @each $i in $image {
     $path: ();

     $images: append($images, $path, comma);
   }

 background-image: $images;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接