我可以在SASS mixin中声明一个新变量吗?

sce*_*tti 7 css variables sass mixins

我有以下SASS mixin:

@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);
}
Run Code Online (Sandbox Code Playgroud)

这个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);
}
Run Code Online (Sandbox Code Playgroud)

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

非常感谢!

Par*_*hum 6

是的,您可以在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);
}
Run Code Online (Sandbox Code Playgroud)