LESS - 替换CSS中的变量

时间:2016-06-01 18:47:19

标签: css less

我有这个LESS代码,其长度从3到25.但输入应该是5.16.2等。在LESS CSS中,我想要它而不是length5.1char ..它是length5-1char ...用于用泛滥替换点。

这是我的代码:

<h2>5.1</h2>
<div class="length5-1chars">
  Width...
</div>
<p>The above bar should be much, much shorter.</p>
<h2>20</h2>
<div class="length20chars">
  Hello
</div>
<h2>15</h2>
<div class="length15chars">
  Hello
</div>
<h2>10</h2>
<div class="length10chars">
  Hello
</div>

LESS:

@fieldLengths: 3, 4, 5, 5.1, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25;

// mixin to iterate over colors and create CSS class for each one
.make-field-lengths(@i: length(@fieldLengths)) when (@i > 0) {
    .make-field-lengths(@i - 1);
    @fieldLength: extract(@fieldLengths, @i); 
    @name: replace(~"@{fieldLength}", "/^\d+\.\d+$/i", "-");
    .length@{name}chars {
        @newWidth:  floor(@fieldLength * 7 + 10);
        width: ~"@{newWidth}px";
      }
}

.make-field-lengths();

div {
  background: #cacaca;
  border: 2px solid black;
  margin-down: 15px;
}

现场演示:http://codepen.io/anon/pen/XKJqyM

如果您转到CSS标签并查看已编译的版本,当它应该说{{1}时,您会看到仍然.length5.1chars }

1 个答案:

答案 0 :(得分:0)

我发现如果我换了:

@name: replace(~"@{fieldLength}", "/^\d+\.\d+$/i", "-");

用这个:

@name: ~`"@{fieldLength}".replace(/\./i, '-')`;

这很有效,因为当LESS变量涉及冲突的字符时,这是合适的语法。