2013-10-18 21 views
0

我創建了一堆使用@for循環標題樣式,但我不能讓它與變量名的工作,如下列:嘗試引用一個動態命名變量,SASS

// Some variables (these work fine) 
$h1-size: 3em; 
$h2-size: 2em; 
$h3-size: 1.6em; 
etc... 

// My loop 
@for $i from 1 through 6 { 
    h#{$i} { 
     color: #333; 
     font-size: $h#{$i}-size; // DOESN'T WORK! 
    } 
} 

循環工作 - 但只有當我刪除關於字體大小的部分。我可以指向一個動態構造的變量嗎?

回答

0

我已經研究過這一堆,似乎沒有在文檔中找到任何支持它的東西。我能想出的最好的是以下解決方法:

// First, make sure you've got all your variables declared 
$h1-size: 3em; 
$h2-size: 2em; 
etc... 

// Then, make a list of the variable names 
$sizelist: $h1-size $h2-size $h3-size $h4-size $h5-size $h6-size; 

// Then, use the SASS nth list function. 
@for $i from 1 through 6 { 
    h#{$i} { 
     font-size: nth($sizelist, $i); 
    } 
} 

這將編譯到:

h1 { 
    font-size: 3em; 
} 
h2 { 
    font-size: 2em; 
} 
etc... 
3

你不能做到這一點,可能是不應該。好消息:即將發佈的3.3版本將引入映射類型。

// Some variables (these work fine) 
$header-info: (
    1: (size: 3em), 
    2: (size: 2em), 
    3: (size: 1.6em), 
); 

@for $i from 1 through 6 { 
    h#{$i} { 
     color: #333; 
     font-size: map-get(map-get($header-info, $i), size); 
    } 
}