[英]Less CSS - access part of class name and use in mixin
在Less中,是否可以訪問類名稱的一部分並在mixin中使用?
最好用一個例子解釋一下:
我有一個網格,我已經聲明如下:
.columns (@columns) {
//code here to generate column widths
}
//This is where my problem is:
.column-1 {
.col (1)
}
.column-2 {
.col (2)
}
.column-3 {
.col (3)
}
// etc etc
顯然,這里有很多重復的代碼。 理想情況下,我希望不必聲明第1列,第2列等,並擁有某種方法(也許是正則表達式)來解析類名,並使用破折號后的值自動計算列寬。 我幾乎可以肯定,twitter引導程序正在執行類似的操作,但我無法理解:
.spanX (@index) when (@index > 0) {
(~".span@{index}") { .span(@index); }
.spanX(@index - 1);
}
.spanX (0) {}
我想您會明白的:
.columnX (@index) when (@index > 0) { // Guarded mixin: use this mixin when the condition is true (like an if statement)
(~".column-@{index}") { // outputs .column-0 as a class name
.col(@index); // for the contents, use the col mixin
} // which class you are doing
.columnX(@index - 1); // Recursive call to the same mixin, going down by 1
}
.columnX (0) {} // Default implementation so that when .columnX(0) is called, a matching mixin is found.
.col (@index) {
// actual css that will be applied to column-1 if @index is 1
width: @index * 10px; // for example
}
.columnX(3); // number of columns you want
編輯 (錯過了;
的.columnX(3);
編輯增加了更多的評論
所有這些都將產生結果:
.column-3 {
width: 30px;
}
.column-2 {
width: 20px;
}
.column-1 {
width: 10px;
}
這與@sherbrow的答案基本相同,但更為簡潔,不會出錯。 考慮這是一個很長的解釋性評論,以支持他的正確答案-遠遠不止於評論!
您將使用像這樣的LESS循環混合作為中間幫助程序,然后調用它指定您要生成的類的數量。 這是.column-1
, .column-2
和.column-3
。 如果要說的話,您希望最多增加四列:只需執行.columns(4)
而不是.columns(3)
[第9行]。 要增加到五列,只需執行.columns(5)
。
1 // we'll call this if we want to build columns
2 .columns(@i) when (@i > 0) {
3 .column-@{i} {
4 .col(@i)
5 }
6 .columns(@i - 1)
7 }
8 // for example, here we build columns 1-3
9 .columns(3);
這將編譯為
.column-1 {.col(1)}
.column-2 {.col(2)}
.column-3 {.col(3)}
(您的問題假設已經有一個mixin .col(@x)
所以我也假設這樣做。有關如何跳過該額外步驟的信息,請參見4。 )
這是正在發生的事情:
.columns(3)
[第9行]將我們發送到.columns(@i)
mixin [第2行],將變量@i
賦值為3
。 @i
(3)大於0 [第2行],所以我們滿足了后衛的要求,並且被允許經過{
[第2行]。 .column-@{i} {...}
[第3-5行]是此mixin將輸出的內容。
@i
為3,因此輸出為.column-3 {.col(3)}
@{i}
語法用於將變量的值作為字符串插入 .col(@x)
,也可以直接在此處放置樣式,例如(là .column-@{i} {width: @i * 10px}
sherbrow) .column-@{i} {width: @i * 10px}
.columns(@i - 1)
.columns(3 - 1)
==> .columns(2)
.columns(3 - 1)
==> .columns(2)
。 @i
(現在為2)大於零,因此允許輸入.column-2 {.col(2)}
(其中.col(2)
立即編譯,因此您編譯的CSS實際上讀取的是.column-2 { the.col(2)styles }
) @i
不大於0(即在.columns(1)
之后停止)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.