【问题标题】:Refactor LESS code with styles targeting color classes使用针对颜色类的样式重构 LESS 代码
【发布时间】:2014-09-08 12:48:46
【问题描述】:

我声明了一堆颜色变量:

@green: #00a75c;
@darkgreen: #118335;
@blue: #0099ff;
@orange: #f7931e;
@sapphire: #303a96;
@gray: #4d4d4d;

我使用的 CMS 将每种颜色都作为一个选项。 因此,生成的 html 将具有这些颜色名称之一作为同级。会生成这样的东西:

<div class="thing orange">
</div>

这是我目前在 less 代码中定位元素的方式:

.thing{
  &.orange{
    color: @orange;
    border: @orange solid 1px;
  }
  &.blue{
    color: @blue;
    border: @blue solid 1px;
  }
  &.sapphire{
    color: @sapphire;
    border: @sapphire solid 1px;
  }
  &.green{
    color: @green;
    border: @green solid 1px;
  }

  &:hover{
    text-decoration: none;
    color: white;
    &.orange{background-color: @orange;}
    &.blue{background-color: @blue;}
    &.sapphire{background-color: @sapphire;}
    &.green{background-color: @green;}
  }
}

重构它的最佳方法是什么?我需要制作小的mixin,一个巨大的mixin吗?我可以以某种方式循环颜色吗?

【问题讨论】:

标签: css html refactoring less stylesheet


【解决方案1】:

基于来自seven-phases-max 的 cmets,这里是一个示例实现。

@colours:
    'green' #00a75c,
    'darkgreen' #118335,
    'blue' #0099ff,
    'orange' #f7931e,
    'sapphire' #303a96,
    'gray' #4d4d4d;

.generate-colour-classes(@index: length(@colours)) when (@index >0) {
    @colour: extract(@colours, @index);
    @property-name: e(extract(@colour, 1));
    @property-value: extract(@colour, 2);
    .generate-colour-class(@property-name; @property-value);
    .generate-colour-classes(@index - 1);
}

.generate-colour-class(@name; @value){
    &.@{name} {
        color: @value;
        border: @value solid 1px;
    }
}

.thing {
    .generate-colour-classes();    
}

【讨论】:

    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 2013-07-25
    • 2018-06-13
    • 2011-08-22
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多