2013-10-18 20 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); 
    } 
}