SASS / SCSS内容功能

时间:2017-09-20 10:52:04

标签: css function sass

我有这个SCSS代码:

@include m(messages){
    @include e(btn){
        &:not([aria-expanded="true"]):hover{
            background-color: rgba(66, 143, 222, 0.11);
        }
        &[aria-expanded="true"],
        span{
            background-color: $color_dark_blue;
            box-shadow:0 2px 5px rgba(66, 143, 222, 0.2);
        }
        &[aria-expanded="true"]{
            span{
                color:$color_dark_blue;
            }
        }
    }
    @include e(header){
        background-color:$color_dark_blue;
    }
}

@include m(reminders){
    @include e(btn){
        &:not([aria-expanded="true"]):hover{
            background-color: rgba(255, 208, 23, 0.11);
        }
        &[aria-expanded="true"],
        span {
            background-color: $color_yellow;
            box-shadow:0 2px 5px rgba(255, 208, 23, 0.2);
        }
        &[aria-expanded="true"]{
            span{
                color:$color_yellow;
            }
        }
    }
    @include e(header){
        background-color:$color_yellow;
    }
}

我有许多类似的@include,唯一不同的是颜色和修饰名称。 我想编写像

这样的函数
notificator('messages', $color_dark_blue);
notificator('reminders', $color_yellow);

如何在SASS / SCSS中实现此功能?

1 个答案:

答案 0 :(得分:1)

我尝试重新构建mixins和标记以尝试解决您的问题 这就是我得到的

$color_dark_blue: #428fde;
$color_yellow: #ffd017;
$color_default: #ccc;

@mixin m($type: default) {
  @if ($type == messages) {
    @include e(btn, $color_dark_blue)
  } @elseif ($type == reminders) {
    @include e(btn, $color_yellow)
  } @elseif ($type == default) {
    @include e(btn, $color_default)
  } @else {
    @error "Invalid $type value. Please use 'messages', 'reminders', or 'default'.";
  }
}

@mixin e($type: btn, $color: $color_default) {
  @if ($type == btn) {
    &:not([aria-expanded="true"]):hover{
      background-color: rgba($color, 0.11);
    }
    &[aria-expanded="true"],
    span {
      background-color: $color;
      box-shadow:0 2px 5px rgba($color, 0.2);
    }
    &[aria-expanded="true"]{
      span{
        color:$color;
      }
    }
  } @elseif ($type == header) {
    background-color:$color;
  } @else {
    @error "Two inputs required $type and $color. Please use 'btn' or 'header' for $type and any color for $color. If you dont enter color, default value will be added";
  }
}

.button {
  @include m();
}

Codepen示例here.请记住,我使用了随机标记,并且我在这里使用了示例mixins:)