我正在学习SASS,并且我正在尝试将数据集合(数组)传递到@mixin
基于此的过程中.我遇到的麻烦是定义数据结构以将值传递给@mixin
这是一些伪代码:
@mixin roundcorners($collection) {
$collectionLength = length(collection);
@for($i from 0 to $collectionLength) {
border-#{$collection[$i]}-radius: 9px;
}
}
.mybox {
@include roundcorners(['top-right','bottom-left']);
}
期望的输出是这样的:
.mybox {
border-top-right-radius: 9px;
border-bottom-left-radius: 9px;
}
Ben*_*ull 16
SASS与数组最接近的是一个列表,您可以使用@each指令进行迭代,如下所示:
@mixin roundcorners($collection: (top-left, top-right, bottom-right, bottom-left), $radius: 0)
@each $corner in $collection
border-#{$corner}-radius: $radius
Run Code Online (Sandbox Code Playgroud)
http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#each-directive
我已经使用字符串插值将列表条目的值放入规则本身 - 我不完全确定这是合法的,但我不在我的开发中.机器检查.
我还在参数上使用了默认值,这意味着您可以传入自定义半径.如果您确实通过了列表中的任何一个角落,您将清除整个默认列表(我认为这是您想要的,但需要注意的事项).
另一种更简单的方法可能是:
@mixin rounded($topLeft:false, $topRight:false, $bottomRight:false, $bottomRight:false)
@if $topLeft != false
border-top-left-radius: $topLeft
@if $topRight != false
border-top-right-radius: $topRight
@if $bottomRight != false
border-bottom-right-radius: $bottomRight
@if $topLeft != false
border-bottom-left-radius: $topLeft
Run Code Online (Sandbox Code Playgroud)
通过设置默认值,您可以调用此mixin,如:
@include rounded(false, 9px, false, 9px)
Run Code Online (Sandbox Code Playgroud)
使用'false'而不是0作为默认值意味着您不会创建比您需要的更多的radius规则.这也意味着如果需要,您可以覆盖并将角设置回0范围.
这就是我解决它的方法,并允许您设置不同的半径.
@mixin border-radius($radius:5px){
@if length($radius) != 1 {
$i:1;
//covers older modzilla browsers
@each $position in (topleft, topright, bottomright, bottomright) {
-moz-border-radius-#{$position}:nth($radius, $i);
$i:$i+1;
}
//Covers webkit browsers
-webkit-border-radius:nth($radius, 1) nth($radius, 2) nth($radius, 3) nth($radius, 4);
//Standard CSS3
border-radius: nth($radius, 1) nth($radius, 2) nth($radius, 3) nth($radius, 4);
} @else {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
border-radius: $radius;
}
}
Run Code Online (Sandbox Code Playgroud)
这意味着您可以将所有半径设置为相同:
@include border-radius(5px)
Run Code Online (Sandbox Code Playgroud)
或者像这样不同:
@include border-radius((5px, 0, 5px, 0))
Run Code Online (Sandbox Code Playgroud)
希望保持你生成的CSS简洁:)