首页 > 解决方案 > 如何从 sass mixin 循环内容指令?

问题描述

我正在尝试编写一个 SASS mixin 来动态循环遍历元素中的项目数,然后应用自定义动画。

// MIXIN
@mixin staggerAnimation($el: $animated-elem) {
    @for $i from 1 through 4 {
        #{$el}:nth-child( #{$i} ) {
            @content
        }
    }
}

// Usage from external SASS file
$animated-elem: '.item';
@include staggerAnimation($animated-elem) {
    // This property needs to be different based on the usage
    animation: FadeIn 1s #{$el * 0.35}s ease 1 both;
}

标签: cssfor-loopsassmixins

解决方案


使用内容块参数(在最新版本的 Dart Sass 中可用)您可以将$i值传递给@content块。

// MIXIN
@mixin staggerAnimation($el: $animated-elem) {
    @for $i from 1 through 4 {
        #{$el}:nth-child( #{$i} ) {
            @content($i)
        }
    }
}

// Usage from external SASS file
$animated-elem: '.item';
@include staggerAnimation($animated-elem) using ($i) {
    // Then you can use the $i variable however you wish in here
    animation: FadeIn 1s #{$i * 0.35}s ease 1 both;
}

如果需要,您甚至可以传递这两个变量(例如@content($i, $el)using ($i, $el)),只需确保它们在两个地方的顺序相同。

注意:除非您使用最新的 Dart Sass 编译器来编译您的 scss,否则这不起作用,这是一个非常新的语言功能,在撰写本文时它尚未实现到 Node Sass 中。


推荐阅读