亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Less中循環遍歷變量名稱數組

在Less中循環遍歷變量名稱數組

慕婉清6462132 2019-11-30 13:38:38
在我們的應用程序中,我們有一個預設的顏色列表,用戶可以從中選擇顏色,并且與該用戶相關的所有內容都將具有該顏色。在整個應用程序中,我們將提供帶有顏色作為類名稱附加的各種模塊。例如。<div class="example_module green">  ...</div>我們在CSS中使用LESS。在許多地方,我們正在做這樣的事情:.example_module.green { background: @green; }.example_module.red { background: @red; }.example_module.blue { background: @blue; }etc我希望能夠將所有這些顏色名稱設置為數組并對其進行迭代。如果將來添加顏色,則只需將其添加到一個位置。偽代碼:@colors: ['green', 'red', 'blue'];for each @color in @colors {  .example_module.@color { background: @color; }} LESS是否甚至支持這種功能?
查看完整描述

3 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

請參閱循環。例如(假設@green,@red,@blue變量別處定義):


@colors: green, red, blue;


.example_module {

    .-(@i: length(@colors)) when (@i > 0) {

        @name: extract(@colors, @i);

        &.@{name} {background: @@name}

        .-((@i - 1));

    } .-;

}

---

在Modern Less中,借助Lists插件可以更直接:


@colors: green, red, blue;


.for-each(@name in @colors) {

    .example_module.@{name} {

        background: @@name;

    }

}

---

在Legacy Less中,語法糖可以使用:


@import "for";


@colors: green, red, blue;


.example_module {

    .for(@colors); .-each(@name) {

        &.@{name} {background: @@name}

    }

}

"for"可以在此處找到導入的代碼段(這只是遞歸的Less循環的包裝mixin)(此處和此處都帶有示例)。


查看完整回答
反對 回復 2019-11-30
?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

這個mixin對我來說很好用。第二個參數是可以訪問當前迭代元素(@value)和索引(@i)的代碼塊。


定義mixin:


.for(@list, @code) {

    & {

        .loop(@i:1) when (@i =< length(@list)) {

            @value: extract(@list, @i);


            @code();


            .loop(@i + 1);

        }


        .loop();

    }

}

使用:


@colors: #1abc9c, #2ecc71, #3498db, #9b59b6;


.for(@colors, {

    .color-@{i} {

        color: @value;

    }

});

結果CSS:


.color-1 {

  color: #1abc9c;

}

.color-2 {

  color: #2ecc71;

}

.color-3 {

  color: #3498db;

}

.color-4 {

  color: #9b59b6;

}


查看完整回答
反對 回復 2019-11-30
?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

使用現代的LESS(> = 3.7),可以使用內置each函數:


/* (assuming @clr-green, @clr-red, @clr-blue variables are defined elsewhere) */

@colors: {

  green: @clr-green;

  red: @clr-red;

  blue: @clr-blue;

}


each(@colors, {

  .example_module.@{key} {

    background: @value;

  }

});


查看完整回答
反對 回復 2019-11-30
  • 3 回答
  • 0 關注
  • 2500 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號