2017-05-09 41 views
3

我想在Sass中创建一个mixin来生成多个背景,问题是背景的数量是未知的,它可以是3,4或甚至是5.在这里,我尝试和失败。使用SASS创建多个背景mixin

@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); 

我不知道如何解决这个问题,因为我还在上海社会科学院性学习的。请有人赐教给我。

回答

3

您正确的方向!但是你的语法和逻辑稍微偏离。这是我想出的:

@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

哦哇,谢谢你的回答,它是完美的!也谢谢你的建议:) –