SASS偏移位置混合麻烦

问题描述 投票:0回答:1

在过去的几个小时里,我一直在尝试制作偏移定位mixin。我一直在努力解决很多错误,我无法理解错误。

这是最新版本,

@function is-offset-prop-valid($value) {
    $values: auto initial inherit 0;

    @return (type-of($value) == number and not unitless($value)) 
          and (index($values, $value) != false);
}

@mixin position($position, $args) {
    $offsets: top right bottom left;

    @each $offset in $offsets {
        $i: index($args, $offset);
        @if $i == length($args) {
            @error "Empty offset values not allowed";
        } else {
            @if is-offset-prop-valid(nth($args, $i+1)) {
                #{$offset}: nth($args, $i+1);
            } else {
                @error "Set value #{nth($args, $i+1)} not a valid property for #{$offset}";
            }
        }
    }

    positon: $position;
}

通常我会将nth($args, $i + 1)设置为变量,但为了这个例子,我就这样离开了它。

当我使用mixin时

.abs {
  @include position(absolute, top 10px);
}

我从内部if语句中得到此错误:

Set value 10px not a valid property for top
css sass mixins
1个回答
0
投票

我修复了你的代码并重新编写了一下。 Sassmeister demo

起初,is-offset-prop-valid函数现在更具可读性。 其次,mixin position确实循环通过参数($args),而不是通过$offsets。我添加了更多的参数检查(查看注释)。你需要在@之前写else符号:@else

@function is-offset-prop-valid($value) {
  $values: auto initial inherit 0;

  $is-numder: type-of($value) == number;
  $is-unitless: unitless($value);
  $match-default-values: index($values, $value) != null;

  @return ($is-numder and not $is-unitless) or $match-default-values;
}

@mixin position($position, $args...) {
  $offsets: top right bottom left;

  @if length($args) == 0 {
    @error "Empty offset values not allowed.";
  }

  @each $arg in $args {
    // Check offset key-value pair
    @if length($arg) != 2 {
      @error "Invalid pair offset-name: offset-value.";
    }

    $offset: nth($arg, 1);
    $value:  nth($arg, 2);

    // Check offset name parameter
    @if index($offsets, $offset) == null {
      @error "Invalid offset name: `#{$offset}`.";
    }
    // Check offset value parameter 
    @if not is-offset-prop-valid($value) {
      @error "Set value `#{$value}` not a valid property for `#{$offset}`.";
    }

    #{$offset}: $value;
  }

  position: $position;
}

.abs {
  @include position(absolute, top 10px, left 23px);
}

但在我看来,一个简单的设定位置更简单,更容易理解:

.abs {
  top: 10px;
  left: 23px;
  position: absolute;
}
© www.soinside.com 2019 - 2024. All rights reserved.