【问题标题】:How to define Sass mixins with variable arguments如何使用可变参数定义 Sass 混合
【发布时间】:2014-04-02 04:08:24
【问题描述】:

在lesscss中,我可以像这样编写mixin,这样使用一个参数调用.myMixin(@a)使用第一个mixin,使用两个参数调用它.myMixin(@a, @b)使用第二个版本的mixin。

.myMixin(@paramOne) {
  // do something with the single-parameter version of mixin
}

.myMixin(@paramOne, @paramTwo) {
  // do something with the two-parameter version of mixin
}

我如何在 sass 中做同样的事情? 或者在 sass 世界中是否有更好的方法来实现这一点?

【问题讨论】:

  • 我也很想发表我的看法 :) 但是对于这个项目,sass 是首选技术,我无法改变它。
  • 了解您要解决的问题需要 2 个具有相同名称和不同参数的 mixin 会很有帮助。
  • 这对于边距、内边距和任何 css 属性很有用,让您可以在普通 css 中使用多个参数定义它们。例如,margin: 5pxmargin: 5px 10px
  • 您可以在参数中传递一个列表并在您的 mixin 中执行此检查以了解该参数是单个值还是列表:@if type-of( $param1 ) == list
  • @bejonbee 既然可以拨打foo(5px 10px),为什么还要拨打foo(5px, 10px)?听起来您正在尝试解决错误的问题。

标签: css sass less


【解决方案1】:

您可以将第二个参数设置为false 作为默认值,并在您的mixin 中执行@if 语句。

@mixin myMixin( $param1, $param2:false ){
    @if $param2 == false{
        // Do something
    }
    @else{
        // Do something with both parameters
    }
}

编辑:这是我用来将 px 单位转换为 em 单位的自定义函数。您可以将列表或单个值作为参数传递。您还可以设置基数和行高。也许你可以在这个函数中找到一些技巧。

你可以这样使用它:emify(10px 16px, 16px)

这将输出:0.625em 1em

/**
*
* Emify
*    Transform px unit into em
* defaults:
*    base: 16
* usage:
*    emify(unit)
*    emify(unit, base)
*    emify(unit, line-height, base)
* examples:
*    emify(16px) = 1em
*    emify(16px, 10px) = 1.600em
*    emify(16px, 10px, 10px) = 1.600em / 1em
*
**/    
@function emify( $target, $lineheight: null, $base: null ) {

    @if $base == null and $lineheight == null { $base: 16 }
    @if $base == null and $lineheight != null { $base: $lineheight }

    [...]

}

【讨论】:

  • 谢谢@lefoy,你的emify 功能澄清了很多。
  • 或者使用variable arguments option:@mixin foo($args...)
  • 不知道变量参数,谢谢分享。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-26
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 2018-11-19
相关资源
最近更新 更多