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

标签 css variables sass less

我目前正在将代码从 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/

相关文章:

variables - 将客户端 js 变量传递到服务器端 jscript

angular - 访问 angular 2 组件中的 bootstrap scss 变量

html - 某种编码值得信赖吗?

function - 连接路径和文件

ios - iphone css 显示表不允许文本复制

Python:在方法中解压字典

css - 我如何在 Compass/Blueprint 中组织导入?

css - Foundation zurb nav 未显示在 rails 中

javascript - 使用 JavaScript/CSS3 制作横幅广告的汽车行驶动画

php - 调整浏览器大小时或在移动设备上运行时如何不破坏表格布局