Sass的表達(dá)式和控制命令 if篇

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 后跟一個表達(dá)式,如果表達(dá)式的結(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 的解析機(jī)制。在 <code>.txt1 </code>中,如果不傳入 <code>bold</code>,那么就不會生成 <code>font-weight</code> 相關(guān)的樣式。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,534評論 19 139
  • 英文原文:Sass Basics: Control Directives and Expressions譯者:南北...
    IT程序獅閱讀 247評論 0 2
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,638評論 18 399
  • 我們什么都沒有,唯一的本錢就是青春,夢想讓我與眾不同,奮斗讓我改變命運(yùn)。 別人的流言蜚語傷害不了我們,真正能傷害我...
    微笑中沉默的野牛閱讀 1,295評論 2 3
  • 營里二中三連 東平 簡書 今天是營里二中軍訓(xùn)的第二天,同學(xué)們的訓(xùn)練熱情依然很高漲,特別是在訓(xùn)練捕俘刀...
    東平教官閱讀 141評論 0 0

友情鏈接更多精彩內(nèi)容