lessのloop(ループ)メソッドを使用してクラス名に基づいて要素を生成

4507 ワード

lessは強力なcssスーパーセットであり、cssコードの書き込みを容易にすることができます.lessは簡単なタグ言語ではなく、多くの現代言語の特性を持っています.分岐とループを含めて、ここではループを使用して要素の自動化生成を行います.
次のコードにはlessの知識が必要です:less中国語網
このような要素を生成する必要がある場合があります.
            <div class="item introduction">
                <div class="split-intro intro-1">div>
                <div class="split-intro intro-2">div>
                <div class="split-intro intro-3">div>
                <div class="split-intro intro-4">div>
            div>

ここではulを使用してリストを生成できますが、これらの要素の中には他のdivが配置される場合がありますので、ここではしばらくリストを使用しません.この4つのネストされたdiv要素にそれぞれの背景画像を追加する必要があります.原生のcssでは、次のように書くかもしれません.
.introduction .intro-1 {
    background-image: url("######.jpg");
}
.introduction .intro-2 {
    background-image: url("######.jpg");
}
.introduction .intro-3 {
    background-image: url("######.jpg");
}
.introduction .intro-4 {
    background-image: url("######.jpg");
}

ここでは、この4つの要素の背景画像を手動で指定する必要があります.要素が少ない場合や、ページを変更する必要がない場合は問題ないようですが、修正するときは、これらの要素の背景画像を変更するurlが1つずつ必要で、多くの要素であれば面倒です.ここでlessのループを使用して簡単な設定を実現できます.
//  
.intro-loop(@n, @i:1) when (@i <= @n) {
    .intro-@{i} {
        img {
            background-image: url("../images/intro-@{i}.jpg");
        }
    }
    .intro-loop(@n, (@i + 1));
}
//  
.introduction {
    .intro-loop(4);
}

//   less          ,            
.loop(@counter) when (@counter > 0) {
    .loop((@counter - 1));
    width: (10px + @counter);
}

これにより、画像のパスをすぐに変更したり、新しい要素を追加したりすることができます.