我目前正在将代码从 SASS 转换为 LESS。
我对以下代码行有疑问:
&[data-rating = "@{counter - 0.5}"] { // THIS DOES NOT WORK
我如何使用变量并从我的计数器 var 中减去 0.5,并将它放在一对引号中,以便它可以位于 HTML 数据属性中。
我包含了两个代码示例,因此您可以获取代码并运行它以查看我的结果。
SASS:
.reviews-stars {
display: inline-block;
@for $i from 1 through 5 {
&[data-rating = "#{$i}"] {
.star:nth-child(-n + #{$i}):before {
color: green;
}
}
&[data-rating = "#{$i - 0.5}"] {
.star:nth-child(-n + #{$i}):before {
color: red;
}
}
}
}
减少:
.looper-review-stars(@counter) when (@counter > 0) {
.looper-review-stars((@counter - 1)); // next iteration
&[data-rating = "@{counter}"] { // THIS WORKS
.star:nth-child(-n + @{counter}):before { // THIS WORKS
color: green;
}
}
// THIS DOES NOT WORK IT RETURNS THE STRING "@{counter - 0.5}"
&[data-rating = "@{counter - 0.5}"] { // THIS DOES NOT WORK
.star:nth-child(-n + @{counter}):before { // THIS WORKS
color: red;
}
}
}
.reviews-stars {
display: inline-block;
.looper-review-stars(5); // launch the loop
}
最佳答案
您可以像下面的代码片段一样使用临时变量来完成。由于选择器是字符串,我认为最好让所有数学运算远离它并放在单独的语句中。
.looper-review-stars(@counter) when (@counter > 0) {
.looper-review-stars((@counter - 1)); // next iteration
&[data-rating = "@{counter}"] {
.star:nth-child(-n + @{counter}):before {
color: green;
}
}
@temp: @counter - .5; /* temporary variable */
&[data-rating = "@{temp}"] {
.star:nth-child(-n + @{counter}):before {
color: red;
}
}
}
.reviews-stars {
display: inline-block;
.looper-review-stars(5); // launch the loop
}
关于css - 在 "quotes"中的 HTML 数据属性中使用 LESS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40808884/