if()
if() 是 Sass 的一個內(nèi)建函數(shù)迁沫,與之相似的 @if 則是一個內(nèi)建指令痘儡。if() 用來做條件判斷并返回特定值爽航,示例如下:
@mixin test($condition){
$color: if($condition,blue,red);
color:$color;
}
.First{
@include test(true);
}
.Second{
@include test(false);
}
編譯結(jié)果為:
.First {
color: blue; }
.Second {
color: red; }
在上面的例字中横浑,if() 函數(shù)內(nèi)的三個參數(shù)分別代表: 測試條件传藏,測試成功返回值则果,測試失敗返回值
(除了 false 和 null 之外的所有測試條件都被視為測試成功)幔翰。如果使用數(shù)字作為上述示例的條件,同樣會返回測試成功的值:
@if
@if 后跟一個表達式西壮,如果表達式的結(jié)果為 true遗增,則返回特定的樣式,示例如下:
@mixin txt($weight) {
color: white;
@if $weight == bold { font-weight: bold;}
}
.txt1 {
@include txt(none);
}
.txt2 {
@include txt(bold);
}
編譯結(jié)果為:
.txt1 {
color: white; }
.txt2 {
color: white;
font-weight: bold; }
此外款青,我們可以使用 @if ... @else if ... @else 結(jié)構(gòu)來處理多個條件做修,示例如下:
@mixin txt($weight) {
color: white;
@if $weight == bold { font-weight: bold;}
@else if $weight == light { font-weight: 100;}
@else { font-weight: normal;}
}
.txt1 {
@include txt(bold);
}
.txt2 {
@include txt(light);
}
.txt3 {
@include txt(none);
}
.txt4 {
@include txt(normal)
}
編譯結(jié)果如下:
.txt1 {
color: white;
font-weight: bold; }
.txt2 {
color: white;
font-weight: 100; }
.txt3 {
color: white;
font-weight: normal; }
.txt4 {
color: white;
font-weight: normal; }
這里的 <code>.txt3 </code>和<code> .txt4</code> 是用來向各位演示 @if 的解析機制。在 <code>.txt1 </code>中抡草,如果不傳入 <code>bold</code>饰及,那么就不會生成 <code>font-weight</code> 相關(guān)的樣式。