【问题标题】:SASS offset position mixin troublesSASS 偏移位置 mixin 问题
【发布时间】:2018-03-05 21:02:43
【问题描述】:

在过去的几个小时里,我一直在尝试制作偏移定位 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】:

    我修复了您的代码并稍微重写了它。萨斯迈斯特demo.

    起初,is-offset-prop-valid 函数现在更具可读性。
    其次,mixin position 确实循环通过参数 ($args),而不是通过 $offsets。我添加了更多参数检查(查看 cmets)。你需要在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;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多