2017-05-09 93 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

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