有效地使用SAS来保持代码干燥

时间:2017-08-24 10:27:10

标签: sass

我编写了以下代码,但我认为如果我充分发挥SASS的潜力,这可能会更短。

代码:

  &.pos-y-top {
    .dropdown-element {
      top: 0;
      .content-wrapper {
        .content, app-dropdown-content {
          bottom: 0;
        }
      }
    }
  }

  &.pos-y-bottom {
    .dropdown-element {
      bottom: 0;
      .content-wrapper {
        .content, app-dropdown-content {
          top: 0;
        }
      }
    }
  }

  &.pos-x-left {
    .dropdown-element {
      right: 0;
      .content-wrapper {
        .content, app-dropdown-content {
          right: 0;
        }
      }
    }
  }

  &.pos-x-right {
    .dropdown-element {
      left: 0;
      .content-wrapper {
        .content, app-dropdown-content {
          left: 0;
        }
      }
    }
  }

  &.pos-x-left.pos-y-bottom {
    .dropdown-element {
      .content-wrapper {
        .content, app-dropdown-content {
          transform-origin: top right;
        }
      }
    }
  }

  &.pos-x-left.pos-y-top {
    .dropdown-element {
      .content-wrapper {
        .content, app-dropdown-content {
          transform-origin: bottom right;
        }
      }
    }
  }

  &.pos-x-right.pos-y-bottom {
    .dropdown-element {
      .content-wrapper {
        .content, app-dropdown-content {
          transform-origin: top left;
        }
      }
    }
  }

  &.pos-x-right.pos-y-top {
    .dropdown-element {
      .content-wrapper {
        .content, app-dropdown-content {
          transform-origin: bottom left;
        }
      }
    }
  }

我昨天和@each一起试过但是在我完成它之后,代码和这个一样长。

任何人都可以告诉我" smart"写这样的代码的方法?

2 个答案:

答案 0 :(得分:0)

我建议使用参数编写@mixin,然后将其包含在您想要的值中。例如,

@mixin distances($top: 0, $right: 0, $bottom: 0, $left: 0) {
  .dropdown-element {
      top: $top;
      right: $right;
      bottom: $bottom;
      left: $left;
      .content-wrapper {
        .content, app-dropdown-content {
          top: $top;
          right: $right;
          bottom: $bottom;
          left: $left;
        }
      }
    }
}

然后你可以:

&.pos-y-top {
  @include distances(0, initial, 0, initial);
}

这可以节省几行。您可以添加更多参数。这只是一个例子。

答案 1 :(得分:0)

我现在就这样做,但我不确定......它对我来说看起来有点脏和不动:

.dropdown {
  @each $axis, $pos, $originX, $originY in
                  ('y', 'top', 'top', 'right'),
                  ('y', 'bottom', 'bottom', 'right'),
                  ('x', 'left', 'top', 'left'),
                  ('x', 'right', 'bottom', 'left') {
    &.pos-#{$axis}-#{$pos} {
      .dropdown-element {
        @if($pos == 'top') { top: 0; }
        @if($pos == 'bottom') { bottom: 0; }
        @if($pos == 'left') { right: 0; }
        @if($pos == 'right') { left: 0; }
        .content-wrapper {
          .content, app-dropdown-content {
            @if($pos == 'top') { bottom: 0; }
            @if($pos == 'bottom') { top: 0; }
            @if($pos == 'left') { right: 0; }
            @if($pos == 'right') { left: 0; }
            transform-origin: #{$originX} #{$originY};
          }
        }
      }
    }
  }
}