使用 class 名称在 css/less 中动态添加样式
Dynamically add styles in css/less by using class name
有没有一种方法可以通过传入 class 名称在 css/less 文件中动态添加样式?
例如:
<div class="xyz_20"></div>
<div class="xyz_40"></div>
而不是写作:
.xyz_20 {width:20px;} .xyz_40 {width:40px;}
有没有一种方法可以让我写一个 class .xyz_i 并根据 i 值自动添加宽度,例如 .xyz_i {width: i px; }` 不涉及 javascript.
如果有,请提出建议。
据我所知,这是不可能的,但这是内联样式的一个很好的用例:
<div class="xyz" style="width:20px"></div>
如果你想支持有限个宽度,那么你可以使用递归来生成类:
.widthgen(@count) when (@count > 0) {
.widthgen((@count - 10));
.xyz_@{count} {
background-color: red;
width: @count * 1px;
}
}
.widthgen(50);
输出:
.xyz_10 {
background-color: red;
width: 10px;
}
.xyz_20 {
background-color: red;
width: 20px;
}
.xyz_30 {
background-color: red;
width: 30px;
}
.xyz_40 {
background-color: red;
width: 40px;
}
.xyz_50 {
background-color: red;
width: 50px;
}
列出插件
如果您想要支持的宽度不容易以线性模式捕获,您可以使用 lists
插件(安装:npm install -g less-plugin-lists
):
@widths: 10, 20, 40, 50;
.for-each(@i in @widths) {
.xyz_@{i} {
background-color: red;
width: @i * 1px;
}
}
你会编译它:
lessc --lists in.less out.css
你会得到:
.xyz_10 {
background-color: red;
width: 10px;
}
.xyz_20 {
background-color: red;
width: 20px;
}
.xyz_40 {
background-color: red;
width: 40px;
}
.xyz_50 {
background-color: red;
width: 50px;
}
没有
无法编写 类 并期望浏览器从中推断出含义。
完成与此类似的事情的唯一方法是使用 javascript(OP 表示他们现在确实想使用)。
有没有一种方法可以通过传入 class 名称在 css/less 文件中动态添加样式?
例如:
<div class="xyz_20"></div>
<div class="xyz_40"></div>
而不是写作:
.xyz_20 {width:20px;} .xyz_40 {width:40px;}
有没有一种方法可以让我写一个 class .xyz_i 并根据 i 值自动添加宽度,例如 .xyz_i {width: i px; }` 不涉及 javascript.
如果有,请提出建议。
据我所知,这是不可能的,但这是内联样式的一个很好的用例:
<div class="xyz" style="width:20px"></div>
如果你想支持有限个宽度,那么你可以使用递归来生成类:
.widthgen(@count) when (@count > 0) {
.widthgen((@count - 10));
.xyz_@{count} {
background-color: red;
width: @count * 1px;
}
}
.widthgen(50);
输出:
.xyz_10 {
background-color: red;
width: 10px;
}
.xyz_20 {
background-color: red;
width: 20px;
}
.xyz_30 {
background-color: red;
width: 30px;
}
.xyz_40 {
background-color: red;
width: 40px;
}
.xyz_50 {
background-color: red;
width: 50px;
}
列出插件
如果您想要支持的宽度不容易以线性模式捕获,您可以使用 lists
插件(安装:npm install -g less-plugin-lists
):
@widths: 10, 20, 40, 50;
.for-each(@i in @widths) {
.xyz_@{i} {
background-color: red;
width: @i * 1px;
}
}
你会编译它:
lessc --lists in.less out.css
你会得到:
.xyz_10 {
background-color: red;
width: 10px;
}
.xyz_20 {
background-color: red;
width: 20px;
}
.xyz_40 {
background-color: red;
width: 40px;
}
.xyz_50 {
background-color: red;
width: 50px;
}
没有
无法编写 类 并期望浏览器从中推断出含义。
完成与此类似的事情的唯一方法是使用 javascript(OP 表示他们现在确实想使用)。