使用SASS mixin创建多个背景

时间:2017-05-09 03:32:32

标签: css sass

我正在尝试在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 个答案:

答案 0 :(得分: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;
}

这似乎回归了你正在寻找的东西。以下是official docs列表函数 - 我总是忘记一两个,也可能对你有用。

此外,既然你提到你是sass的新手 - 如果你还没有,请查看Sassmeister。它是一个方便的小沙箱,可以快速进行原型设计并在sass中进行尝试;类似于Codepen但更专业一点。这就是我过去常常试验这个问题的原因。

答案 1 :(得分:0)

我相信这是一个更干净的答案。

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

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

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

 background-image: $images;
}