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

时间:2013-10-24 15:43:13

标签: 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);
}

此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);
}

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

非常感谢你!

1 个答案:

答案 0 :(得分: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);
}