使用LESS循环命名变量

时间:2015-04-05 01:39:11

标签: less

我有一系列代表不同主题的颜色。我使用的主题之一是元素的颜色代表它涵盖的主题,元素最多可以引用两个主题。如果元素使用两个主题,则其背景使用渐变而不是平面颜色。例如:

@literatureColor: red;
@mathColor: blue;
.literature{
    background-color: @literatureColor;
}
.math{
    background-color: @mathColor;
}
.literature-math{
    background: linear-gradient(to right, @literatureColor 0%, @mathColor 100%);
}

我希望能够在可能的情况下使用循环动态生成.literature-math(目前使用JS),因为我有20个主题可以涵盖。 LESS循环可以实现吗?从我在循环示例中看到的,只能引用循环变量,我需要能够动态生成类名。

1 个答案:

答案 0 :(得分:1)

据我了解你的问题,你需要某种“交叉产品”。您将需要两个循环来创建类,还需要variables with variable names

示例:

@literatureColor: red;
@mathColor: blue;
@geographyColor: yellow;
@computationalscienceColor: orange;

@classes: literature,math,geography,computationalscience;


.outsideloop(@classes; @iterator: 1) {
    @pre: extract(@classes,@iterator); 

    .insideloop(@pre,@classes,@iterator);

    & when (@iterator < length(@classes)) {
        .outsideloop(@classes,@iterator + 1);
    }
}

.insideloop(@pre,@classes,@preiterator,@iterator: 1) {
    @post: extract(@classes,@iterator);

    & when not (@pre = @post) {
        @precolor: "@{pre}Color";
        @postcolor: "@{post}Color";
        @{pre}-@{post} { 
            background: linear-gradient(to right, @@precolor 0%, @@postcolor 100%); 
        }
    }

    & when (@iterator < length(@classes)) {
        .insideloop(@pre,@classes,@preiterator,@iterator + 1);
    }
}

.outsideloop(@classes);

前面的Less代码将编译成CSS代码,如下所示:

literature-math {
  background: linear-gradient(to right, red 0%, blue 100%);
}
literature-geography {
  background: linear-gradient(to right, red 0%, yellow 100%);
}
literature-computationalscience {
  background: linear-gradient(to right, red 0%, orange 100%);
}
math-literature {
  background: linear-gradient(to right, blue 0%, red 100%);
}
math-geography {
  background: linear-gradient(to right, blue 0%, yellow 100%);
}
math-computationalscience {
  background: linear-gradient(to right, blue 0%, orange 100%);
}
geography-literature {
  background: linear-gradient(to right, yellow 0%, red 100%);
}
geography-math {
  background: linear-gradient(to right, yellow 0%, blue 100%);
}
geography-computationalscience {
  background: linear-gradient(to right, yellow 0%, orange 100%);
}
computationalscience-literature {
  background: linear-gradient(to right, orange 0%, red 100%);
}
computationalscience-math {
  background: linear-gradient(to right, orange 0%, blue 100%);
}
computationalscience-geography {
  background: linear-gradient(to right, orange 0%, yellow 100%);
}