问题描述
如何在LESS中使用@loop或其他方法创建以下类数组
.margin-top--1{
margin-top:-1rem;
}
.margin-top--0-5{
margin-top:-0.5rem;
}
.margin-top-0{
margin-top:0rem;
}
.margin-top-0-5{
margin-top:0.5rem;
}
.margin-top-1{
margin-top:1rem;
}
解决方法
我对LESS不太了解,因此可能有一个更清洁的解决方案,但这至少应该可以工作。
使用循环,就像您尝试过的一样,但是将值中的点替换为破折号,因此选择器是正确的。
要逃避价值:
- 使用格式函数(http://lesscss.org/functions/#string-functions--format)将索引值转换为字符串,
- 使用替换功能(http://lesscss.org/functions/#string-functions-replace)用破折号替换破折号,
- 通过转义函数(http://lesscss.org/functions/#string-functions-e)分配值以去除引号后。
<style type="text/less">
div {
margin: 0;
border: 1px solid black;
background: white;
color: black;
}
@loop-margin-top: 1;
.loop-margin-top (@i) when (@i >= -1) {
@escapedValue: e(replace(%("%s",@i),"\.","-","g"));
.margin-top-@{escapedValue} {
margin-top: ~"@{i}rem";
}
.loop-margin-top(@i - 0.5);
}
.loop-margin-top (@loop-margin-top);
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/less.js/3.12.2/less.min.js"></script>
<div class="margin-top-1">
1
</div>
<div class="margin-top-0-5">
0.5
</div>
<div class="margin-top-0">
0
</div>
<div class="margin-top--0-5">
-0.5
</div>
<div class="margin-top--1">
-1
</div>