在 HTML 数据属性中使用 LESS 变量 "quotes"



我当前正在将代码从sass转换为更少。

我对以下代码行有问题:

&[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
}

最新更新