首页 > 解决方案 > @mixin 通过使用参数选择一个特定的占位符

问题描述

我正在尝试在占位符内使用带有参数的mixin。这个想法是使用一行代码来选择类中的特定占位符。实际上,我不知道是否有另一种更好的方法可以做到这一点,也许是使用函数或其他方法。我正在学习 Sass,所以我正在尝试进行实验。

HTML

<div class='wrap'>
  <div class='box'></div>
  <div class='box'></div>
</div>

SCSS

// VAR
$size-xs: 30px;
$size-s: 50px;
$size-m: 70px;

$color-1: orange;
$color-2: rgb(34,139,86);

@mixin box($val) {
  %box-one {
    width: $size-s;
    height: $size-s;
    background: $color-1;
    margin: auto;
    border-radius: 6px;
  }
  %box-two {
    width: $size-s;
    height: $size-s;
    background: $color-2;
    margin: auto;
    border-radius: 6px;
  }
  .box {
    @extend #{$val} !optional;
  }
}

.wrap {
  width: 100%;
  height: 100px;
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  @include box(box-one);
}

谢谢你!

标签: csssass

解决方案


目前,您的代码无法正常工作,因为您忘记添加%before #{$val}

.box {
  @extend %#{$val} !optional;
}

无论如何,将占位符选择器放在 mixin 中并不是一个好主意,因为每次调用 mixin 时,您都在创建新的选择器。这意味着例如,如果您添加:

.randomSelector {
  @include box(box-one);
}

你会得到:

.wrap .box { ... }
.randomSelector .box { ... }

代替:

.randomSelector .box, .wrap .box { ... }

所以我建议你外部化%box-one%box-two.

最后一件事,如果这两个类之间的唯一区别是background属性,那么使用单个类重新组合公共属性可能会是更好的优化:

.box {
  width: $size-s;
  height: $size-s;
  margin: auto;
  border-radius: 6px;
}

%box-one {
  background: $color-1;
}

%box-two {
  background: $color-2;
}

@mixin box($val) {
  .box {
    @extend %box-#{$val} !optional;
  }
}

.wrap {
  width: 100%;
  height: 100px;
  background: #f5f5f5;
  display: flex;
  justify-content: space-between;
  @include box(one);
}

如果您有更多的框样式,您甚至可以动态创建占位符:

$boxStyles: (
  one: $color-1,
  two: $color-2
);

@each $box, $style in $boxStyles {
  %box-#{$box}  {
    background: $style;
  }
}

推荐阅读