作者:Henry-lau洋 | 来源:互联网 | 2023-05-16 20:59
ImlearningSASSandImtryingtopassacollectionofdata(anarray)intoa@mixinandprocessb
I'm learning SASS and I'm trying to pass a collection of data (an array) into a @mixin
and process based on that. The trouble I'm having is defining the data structure to pass the values into the @mixin
我正在学习SASS,并试图将数据集合(数组)传递给@mixin,并以此为基础进行处理。我遇到的麻烦是定义数据结构,将值传递给@mixin
Here's some pseudo code:
这里有一些伪代码:
@mixin roundcorners($collection) {
$collectiOnLength= length(collection);
@for($i from 0 to $collectionLength) {
border-#{$collection[$i]}-radius: 9px;
}
}
.mybox {
@include roundcorners(['top-right','bottom-left']);
}
The desired output would be this:
期望的产出如下:
.mybox {
border-top-right-radius: 9px;
border-bottom-left-radius: 9px;
}
3 个解决方案
17
The closest thing SASS has to an array is a list, which you can iterate with the @each directive, like so:
SASS与数组最接近的东西是一个列表,您可以使用@each指令对其进行迭代,如下所示:
@mixin roundcorners($collection: (top-left, top-right, bottom-right, bottom-left), $radius: 0)
@each $corner in $collection
border-#{$corner}-radius: $radius
http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#each-directive
http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html每个指示
I've used string interpolation to drop the value of the list entry into the rule itself - I'm not entirely sure that's legal, but I'm not on my dev. machine to check.
我使用了字符串插值将列表项的值放入规则本身——我不完全确定这是否合法,但我不在开发人员机器上检查。
I've also used default values on the arguments, which means you can pass in a custom radius. If you do pass in any corner in the list, you'll clear the whole default list (which I think is what you want, but something to be aware of).
我还对参数使用了默认值,这意味着您可以传递自定义的半径。如果您在列表中的任何一个角落都通过了,您将会清除整个默认列表(我认为这是您想要的,但是需要注意的是)。
A different, simpler way to do this might be:
另一种更简单的方法可能是:
@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
By setting defaults, you can call this mixin like:
通过设置默认值,您可以将这个mixin称为:
@include rounded(false, 9px, false, 9px)
Using 'false' instead of 0 as the default means you don't create more radius rules than you need. It also means you can override and set corners back to 0 radius if you need to.
使用“false”而不是0作为默认值意味着您不会创建超出所需的范围规则。它还意味着如果需要的话,您可以重写并将弯角设置为0半径。