Dynamic class names in LESS

后端 未结 2 1964
独厮守ぢ
独厮守ぢ 2021-02-14 12:19

I have the following bit of LESS code working

            @iterations: 940;
            @iterations: 940;
            @col:2.0833333333333333333333333333333%;
           


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-14 13:00

    This whole question was very helpful to me. I just wanted to post the solution to my problem as the way to do it has changed since LESS v 1.4. LESS Changelog

    Rather than using the ~ sign, you just write out the portion of the name that you want along with the normal @ and variable name with {} surrounding it. So: #class@{variable}.

    For example, my solution using the same sort of loop became such:

    /*Total number of passport inserts*/
    @numInserts: 5;
    /*Total width of the passport foldouts*/
    @passportWidth: 300px;
    /*Change in passport insert width per iteration*/
    @passportWidthDiff: (@passportWidth / @numInserts);
    /*"Array" of colors to select from to apply to the id*/
    @passportColors: 
    blue orange green red yellow 
    purple white teal violet indigo;
    
    /*The faux loop the doesn't end up in the final css
    @index is the counter
    @numInserts is the total number of loops*/
    .loopingClass (@index) when (@index <= @numInserts){
       /*This is the created ID with the index appended to it
       You can also do this with classes such as if 
       we had had ".insert@{index}"*/
       #insert@{index}{
          /*Here are our properties that get adjusted with the index*/
          width: (@passportWidth - (@passportWidthDiff * (@numInserts - @index)));
          height: 50px;
          background-color: extract(@passportColors, @index);
          z-index: (@numInserts - @index);
       }
       /*Here we increment our loop*/
       .loopingClass(@index + 1);
    }
    /*This calls the loop and starts it, I started from 1
    since I didn't want to lead a className starting from 0,
    But there is no real reason not to.  Just remember to
    Change your conditional from "<=" to "<"*/
    .loopingClass(1);
    

    And produces the following:

    #insert1 {
      width: 60px;
      height: 50px;
      background-color: #0000ff;
      z-index: 4;
    }
    #insert2 {
      width: 120px;
      height: 50px;
      background-color: #ffa500;
      z-index: 3;
    }
    #insert3 {
      width: 180px;
      height: 50px;
      background-color: #008000;
      z-index: 2;
    }
    ...
    

提交回复
热议问题