css - SASS偏移位置mixin麻烦

标签 css sass mixins

在过去的几个小时里,我一直在尝试进行偏移定位混合。我一直在为很多错误而苦苦挣扎,我不明白哪里出了问题。

这是最新版本,

@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

最佳答案

我修复了您的代码并稍微重写了它。萨斯梅斯特 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;
}

关于css - SASS偏移位置mixin麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107123/

相关文章:

css 100% 宽度当水平滚动条

html - 如何更改 Foundation Zurb 背景?

html - 居中 CSS 网格元素

c++ - 广义混合

用于基于类的通用 View 的 Django mixins

javascript - 如何在 React 中包含 SVG 文件?

javascript - 当我的动画完成时,transitionend 事件不会触发

php - 在 codeigniter 错误的 View 中加载 css

html - 悬停时倾斜效果错误

html - 使用 less css 的增量文件名