【问题标题】:How to loop through content directive from a sass mixin?如何从 sass mixin 循环内容指令?
【发布时间】:2019-11-12 12:37:45
【问题描述】:

我正在尝试编写一个 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;
}

【问题讨论】:

  • $el * 0.35 应该做什么?
  • 它应该增加动画延迟。在此示例中,我正在创建元素的交错动画
  • 那么,不应该是$i 而不是$el 吗?由于$el 采用$animated-elem 的值,这是一个字符串(选择器),因此您无法从中增加任何内容。但是,对于$i,问题仍然存在,因为您无法将变量从@mixin 传递给@content。但是,您可以使用全局变量,请查看this

标签: css for-loop sass mixins


【解决方案1】:

使用内容块参数(在最新版本的 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 中实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-05
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多