使用 LESS 遍历命名变量

Looping through named variables with 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 循环可能吗?从我在他们的循环示例中看到的,只能引用循环变量,我需要能够动态生成 class 名称。

据我了解你的问题,你需要某种 "cross product"。您将需要两个循环来创建 类 并且还需要 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%);
}