Sprites LESS CSS Variable increment issue

后端 未结 2 1987
猫巷女王i
猫巷女王i 2021-01-15 12:39

I have a problem with sprites background position calculation using a variable:

My code looks something like this:

@counter: 1;

#my-icon-bundle {
.m         


        
2条回答
  •  清酒与你
    2021-01-15 13:15

    Strictly Speaking You Cannot

    Variables in LESS are essentially constants once defined in a particular scope, and so cannot be changed (including incremented). So your @counter: @index + 1; is not incrementing the global variable at all, but rather creating a new value for a local scope @counter variable inside that particular call of .myIconX(). See the documentation on how variables work in LESS.

    Emulated by Recursive Local Variable Setting

    This works, based off information deemed a bug here, but which I do not believe is strictly speaking a bug. At any rate, it can be utilized to meet your needs like so (I just implemented an @row: 1 and tweaked some code to show the calculation working):

    @row: 1;
    
    .init() {
    .inc-impl(1);
    } .init();
    
    .inc-impl(@new) {
    .redefine() {
    @counter: @new;
    }
    }
    
    #my-icon-bundle {
    .my-icons () {
      #my-icon-bundle .myIconX("classX1", @counter);
      #my-icon-bundle .myIconX("classYY1", @counter);
    }
    
    .myIconX(@name) {
       .redefine();
      .inc-impl((@counter + 1));
      @nameText: ~".my-icon-@{name}";
      @{nameText} { #my-icon-bundle .myIcon(@row); }
    }
    
    .myIcon(@row) {
      @x: @row * @counter;
      @y: @row * @counter;
      background-position: -@x -@y;
    }
    }
    
    #my-icon-bundle .myIconX("classX1");
    #my-icon-bundle .myIconX("classX1");
    #my-icon-bundle .myIconX("classYY1");
    

    Output CSS is:

    .my-icon-classX1 {
      background-position: -1 -1;
    }
    .my-icon-classX1 {
      background-position: -2 -2;
    }
    .my-icon-classYY1 {
      background-position: -3 -3;
    }
    

    This demonstrates that with each call of the .myIconX() mixin, it is setting the counter by +1 for the next call.

    Warning: Whether this solution is based on buggy behavior or not is questionable, but if it is a bug, this solution may disappear in the future. For further comments on the limitations of this method, see the discussion here.

提交回复
热议问题