7

我有以下 SASS 混合:

@mixin gradient($start, $end, $fallback: $end, $direction: bottom) {
@if $direction == top {
    $directionOld: bottom;
} @else if $direction == right {
    $directionOld: left;
} @elseif $direction == bottom {
    $directionOld: top;
} @elseif $direction == left {
    $directionOld: right;
}

background: $fallback;
background: -webkit-linear-gradient($directionOld, $start, $end);
background:         linear-gradient(to $direction, $start, $end);
}

这个 mixin 会抛出一个错误,因为 $directionOld 没有定义。我可以修复它,默认情况下将此变量添加到 mixin 参数:

@mixin gradient($start, $end, $fallback: $end, $direction: bottom, $directionOld: top) {
@if $direction == top {
    $directionOld: bottom;
} @else if $direction == right {
    $directionOld: left;
} @elseif $direction == bottom {
    $directionOld: top;
} @elseif $direction == left {
    $directionOld: right;
}

background: $fallback;
background: -webkit-linear-gradient($directionOld, $start, $end);
background:         linear-gradient(to $direction, $start, $end);
}

但这并不像我想要的那样干净,第一个代码中是否有任何错误?

非常感谢!

4

1 回答 1

8

是的,您可以在 Mixin 中定义新变量,但您必须在 if 语句中使用它之前定义它。

我再次编写您的代码:

@mixin gradient($start, $end, $fallback: $end, $direction: bottom) {
    $directionOld:top !default;

    @if $direction == top {
        $directionOld: bottom;
    } @else if $direction == right {
        $directionOld: left;
    } @elseif $direction == bottom {
        $directionOld: top;
    } @elseif $direction == left {
        $directionOld: right;
    }

    background: $fallback;
    background: -webkit-linear-gradient($directionOld, $start, $end);
    background:         linear-gradient(to $direction, $start, $end);
}
于 2013-12-01T07:50:35.003 回答