Имена динамических классов в LESS

У меня есть следующий бит кода LESS, который работает

            @iterations: 940;
            @iterations: 940;
            @col:2.0833333333333333333333333333333%;
            // helper class, will never show up in resulting css
            // will be called as long the index is above 0
            .loopingClass (@index) when (@index > -20) {
                // create the actual css selector, example will result in
                // .myclass_30, .myclass_28, .... , .myclass_1
                (~".gs@{index}") {
                    // your resulting css
                    width: (@index/20+1)*@col;
                }
                // next iteration
                .loopingClass(@index - 60);
            }
            // end the loop when index is 0
            .loopingClass (-20) {}
            // "call" the loopingClass the first time with highest value
            .loopingClass (@iterations);

Он выводит нашу сетку следующим образом:

            .gs940 {
              width: 100%;
            }
            .gs880 {
              width: 93.75%;
            }
            .gs820 {
              width: 87.5%;
            }
            .gs760 {
              width: 81.25%;
            }
            .gs700 {
              width: 75%;
            }

и т.д. и т.п.

Теперь то, что я хочу сделать, это немного математики для имен классов, чтобы создать следующие классы.

            .gs220-700
            .gs280-640
            .gs340-580
            .gs400-520
            .gs460-460
            .gs520-400
            .gs580-340
            .gs640-280
            .gs700-220

и т.д. и т.п.

в основном это будет .(@index) - (920px минус @index)

Но я понятия не имею, возможно ли это.


person R Reveley    schedule 05.06.2012    source источник


Ответы (2)


Я не думаю, что ты далеко. Что я сделал, так это создал вторую переменную внутри миксина с именем @index2. Все, что нужно сделать, это найти значение «920px минус @index», которое вы ищете:

@index2 = (920-@index);

затем это добавляется к имени класса:

(~".gs@{index}-@{index2}") {

Это полный цикл:

.loopingClass (@index) when (@index > 160) {
    @index2 = (920-@index);
    // create the actual css selector, example will result in
    // .myclass_30, .myclass_28, .... , .myclass_1
    (~".gs@{index}-@{index2}") {
    // your resulting css
        width: (@index/20+1)*@col;
    }
    // next iteration
    .loopingClass(@index - 60);
}
// "call" the loopingClass the first time with highest value
.loopingClass (@iterations);

Чтобы получить именно тот набор, который вы ищете (от gs220-700 до gs700-220), просто измените @iterations на 700.

Стоит отметить, что в настоящее время это создаст классы в порядке, обратном тому, как вы указали их в вопросе.

person cchana    schedule 06.06.2012

Весь этот вопрос был очень полезен для меня. Я просто хотел опубликовать решение моей проблемы, так как способ сделать это изменился с LESS v 1.4. Журнал изменений МЕНЬШЕ

Вместо использования знака ~ вы просто записываете нужную часть имени вместе с обычным @ и именем переменной с окружением {}. Итак: #class@{variable}.

Например, мое решение с использованием такого же цикла стало таким:

/*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);

И выдает следующее:

#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;
}
...
person zero298    schedule 03.01.2014
comment
Мне любопытно, как это будет выглядеть, если мы попытаемся вытащить повторяющиеся свойства в один блок. В этом случае вывод, о котором я говорю, будет выглядеть так: #insert1, #insert2, #insert3 { height: 50px; } - person Michael Cordingley; 24.12.2014