Css 在SASS中创建一个集合(数组),用于@for循环
我正在学习SASS,并试图将一组数据(一个数组)传递到一个Css 在SASS中创建一个集合(数组),用于@for循环,css,arrays,for-loop,sass,Css,Arrays,For Loop,Sass,我正在学习SASS,并试图将一组数据(一个数组)传递到一个@mixin中,并在此基础上进行处理。我遇到的麻烦是定义数据结构以将值传递到@mixin 下面是一些伪代码: @mixin roundcorners($collection) { $collectionLength = length(collection); @for($i from 0 to $collectionLength) { border-#{$collection[$i]}-radius:
@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;
}
SASS最接近数组的是一个列表,您可以使用@each指令对其进行迭代,如下所示:
@mixin roundcorners($collection: (top-left, top-right, bottom-right, bottom-left), $radius: 0)
@each $corner in $collection
border-#{$corner}-radius: $radius
我已经使用字符串插值将列表项的值放入规则本身-我不完全确定这是否合法,但我不在我的开发机器上检查
我还在参数上使用了默认值,这意味着您可以传入自定义半径。如果您确实通过了列表中的任何一个角落,您将清除整个默认列表(我认为这是您想要的,但需要注意)
另一种更简单的方法可能是:
@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
通过设置默认值,可以调用此mixin,如下所示:
@include rounded(false, 9px, false, 9px)
使用“false”而不是0作为默认值意味着您不会创建超出需要的半径规则。这也意味着,如果需要,您可以覆盖并将拐角设置回0半径。使用@Beejamin提供的代码,在修复一些语法问题后,我能够设计出以下解决方案
@mixin roundcorners($collection: (top-left, top-right, bottom-right, bottom-left), $radius: 0) {
@each $corner in $collection {
border-#{$corner}-radius: $radius
}
}
@include roundcorners((top-right, bottom-left), 9px);
然而,我更喜欢他的最终解决方案,它允许我为每个角指定不同的半径。我就是这样解决的,并允许您设置不同的半径
@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;
}
}
这意味着您可以将所有半径设置为相同:
@include border-radius(5px)
或者像这样不同:
@include border-radius((5px, 0, 5px, 0))
希望生成的CSS也保持简洁:)谢谢!我不知道
@每一个
,我更喜欢它,而不是我是如何使用@的
!您的替代解决方案似乎更适合我想做的事情,但了解收藏也很好!我搜索了又搜索,只发现有人说这是不可能的。谢谢,伙计-我按照你的说明修复了插值语法。