You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Less mixin生成样式时如何去除选择器名称中的引号

问题原因

你定义的@themes数组中的元素是带单引号的字符串类型,使用extract方法取出值时会保留字符串的引号,插值到类名中就会出现多余的引号。

解决方法

有两种常用方案可以解决这个问题:

方案1:对提取的主题名脱引号

不需要修改@themes的定义,只需要调整循环中@theme变量的赋值逻辑,用Less转义符去掉字符串外层的引号即可:

.createThemes(@n, @i: 1) when (@i =< @n) {
  // 给提取出的字符串脱引号
  @theme: ~"@{extract(@themes, @i)}";
  .dashboard-@{theme} {
    background-color: ~'@{theme-@{theme}}' ;
    color: ~'@{theme-@{theme}-text}';
  }
  .createThemes(@n, (@i + 1));
}

方案2:直接定义无引号的主题列表

一开始定义@themes时就不用加引号,Less支持直接用空格分隔的标识符作为列表元素:

// 去掉所有元素的单引号
@themes: green yellow red brown grey darkBlue navyBlue cyan lightBlue default;
@themes-light: grey lightBlue;
@themes-dark: green yellow red brown darkBlue navyBlue cyan default;

修改后不需要调整循环逻辑,生成的类名就会自动去掉引号。

两种方案最终生成的CSS都会符合预期:

.dashboard-green {
  background-color: #91ab7a;
  color: #fff;
}
.dashboard-yellow {
  background-color: #efdf91;
  color: #00395d;
}
/* 其余主题类格式同理 */

内容的提问来源于stack exchange,提问作者Matthew Daly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:06:04