1

遇到了一个让我发疯的 Sass 问题。基本上我有以下 Sass 代码:

$breakpoints: mobile 320px, tablet 760px, desktop 960px;

@mixin setbreakpoint($point) {
    @each $breakpoint in $breakpoints {
      @if $point == #{nth($breakpoint, 1)} {
        @media (min-width: #{nth($breakpoint, 2)}) { @content; }
      }
    }
}

.page-wrap {
  width: 75%;
  @include setbreakpoint(mobile) { content:"mobile"; }
  @include setbreakpoint(tablet) { content:"tablet"; }
  @include setbreakpoint(desktop) { content:"desktop"; }
}

@each $breakpoint in $breakpoints {
    .page-wrap-#{nth($breakpoint, 1)} { content:#{nth($breakpoint, 2)}; }
}

输出以下CSS:

.page-wrap {
  width: 75%; }
  @media (max-width: 320px) {
    .page-wrap { content: "mobile"; } }
  @media (max-width: 760px) {
    .page-wrap { content: "mobile"; } }
  @media (max-width: 960px) {
    .page-wrap { content: "mobile"; } }
  @media (max-width: 320px) {
    .page-wrap { content: "tablet"; } }
  @media (max-width: 760px) {
    .page-wrap { content: "tablet"; } }
  @media (max-width: 960px) {
    .page-wrap { content: "tablet"; } }
  @media (max-width: 320px) {
    .page-wrap { content: "desktop"; } }
  @media (max-width: 760px) {
    .page-wrap { content: "desktop"; } }
  @media (max-width: 960px) {
    .page-wrap { content: "desktop"; } }

.page-wrap-mobile {
  content: 320px; }

.page-wrap-tablet {
  content: 760px; }

.page-wrap-desktop {
  content: 960px; }

问题是:为什么 mixin 每个循环产生 9 个结果,而基本类每个循环产生 3 个结果?

4

1 回答 1

2

这是因为这里的 if 语句:

@if $point == #{nth($breakpoint, 1)} {
    @media (min-width: #{nth($breakpoint, 2)}) { @content; }
}

您正在比较不同类型的变量。无论出于何种原因,编译器总是认为它们是相等的。您所要做的就是删除字符串插值,它可以按预期工作:

@if $point == nth($breakpoint, 1) {
    // You don't need when displaying the value either...
    @media (min-width: nth($breakpoint, 2)) { @content; }
}
于 2013-01-29T14:10:22.057 回答