【问题标题】:call sass mixins from sass functions从 sass 函数调用 sass mixins
【发布时间】:2017-09-08 15:20:42
【问题描述】:

我有一个生成选择器名称的 sass mixin:

@mixin rocks($name){
  #{$name}-rocks {
    @content;
  }
}

通过调用 mixin 来调用:

@include rocks(dave){
  color: red;
}

我想为我创建一个调用此 mixin 的自定义函数,以将语法缩短为:

rocks(dave){
  color: red;
}

是否可以 1. 在选择器之外调用 sass @functions?和 2. 从中调用 mixins?大致如下:

@function rocks($name){
  @include @rocks($name)
}

如果可能的话,我更喜欢自定义 sass 函数而不是自定义 ruby​​ 函数。谢谢!

【问题讨论】:

    标签: sass


    【解决方案1】:

    没有,也没有。 Sass 中的函数只能返回值,不能用于创建 CSS。这就是 mixins 的用途:创建 mixins 来调用其他 mixins。

    【讨论】:

    • 我知道用 Ruby 编写的自定义函数可以做到这一点,罗盘有一些像“nest(...)”这样的。希望 sass 脚本函数可以实现。
    【解决方案2】:
    @function class($name) {
      @return $name;
    }
    
    @mixin className($classname) {
      .#{class($classname)} {
        @content;
      }
    }
    
    @mixin concatinate($classname2) {
      &.#{class($classname2)} {
        @content;
      }
    }
    
    @mixin parent($classname1) {
      .#{class($classname1)} & {
        @content;
      }
    }
    
    @mixin withparent($classname1) {
      @at-root .#{class($classname1)}#{&} {
        @content;
      }
    }
    
    @include className(red) {
      color: red;
    
      @include className(check) {
        color: green;
    
        @include concatinate(bcd) {
          color: green2;
    
          ul {
            li {
              color: red;
    
              & {
                color: blue;
              }
    
              @include withparent(colorwe) {
                display: none;
              }
            }
          }
    
          @include parent(efg) {
            color: green1;
          }
        }
      }
    
    
      @include className(blue) {
        color: blue;
      }
    }
    

    【讨论】:

    • 是的,你可以在 sass V3 中选择带有 mixin 和函数的选择器
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    • @DonaldDuck 感谢您的反馈;但我只有这个解决方案才能从 mixins 中调用选择器名称;所以
    【解决方案3】:

    @DonaldDuck 感谢您的反馈。我个人认为没有必要通过mixins调用选择器,如果有人尝试这样做,它将通过使用这些mixins来解决。

    例如:

    //call a class
    @include className(one) { 
      properties..
    }//o/p    .one { properties..}
    //add another class with existing one
    @include className(one) {
      @include concatinate(two) {
        @include className(three) {
          properties...
        }
      }
    }//o/p   .one.two .three { properties...}
    //add parent to hierarchy
    @include className(one) {
      @include parent(two) {
        properties..
      }
    }//o/p .two .one { properties..}
    //add class with top of the hierarchy
    @include className(one) {
      @include className(two) {
        @include withparent(three) {
          properties...
        }
      }
    } o/p  .one.three .two { properties..}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 2012-06-21
      • 2020-05-29
      相关资源
      最近更新 更多