html - 我怎样才能用 LESS 而不是直接的 CSS 构建一个灵活的评级小部件?

标签 html css less

我发现了这个灵活的单图像评级小部件,由 AirBnB 使用 SASS 构建.我想用 LESS 创建类似的东西。我知道我可以写出 CSS,但我想用 LESS 动态地完成它。我的主要问题似乎是动态添加计数器 _1 ... _10 到类 (.filled_1 ... filled_10)。这在 LESS 中可能吗?

这是有效的 SASS 代码:

$starWidth: 44px;
$starOffset: 0 -43px;
$numStars: 5;
$steps: 2;
$total: $numStars * $steps;

@mixin filled($n: 0) {
  width: ($starWidth / $steps) * $n;
}

.stars {
  background: url(/images/sprite.png) repeat-x top left;
  height: 43px;

  &.empty {
    background-position: $starOffset;
    width: $numStars * $starWidth;
  }

  @for $i from 0 through ($total) {
    &.filled_#{$i} { @include filled($i) }
  }
}

结果是这样的 CSS 代码:

.stars {
  background: url(/images/sprite.png) repeat-x top left;
  height: 43px; }
  .stars.empty {
    background-position: 0 -43px;
    width: 220px; }
  .stars.filled_0 {
    width: 0px; }
  .stars.filled_1 {
    width: 22px; }
  .stars.filled_2 {
    width: 44px; }
  .stars.filled_3 {
    width: 66px; }
  .stars.filled_4 {
    width: 88px; }
  .stars.filled_5 {
    width: 110px; }
  .stars.filled_5 {
    width: 132px; }
  .stars.filled_7 {
    width: 154px; }
  .stars.filled_8 {
    width: 176px; }
  .stars.filled_9 {
    width: 198px; }
  .stars.filled_10 {
    width: 220px; }

我怎样才能执行相同的循环并包含在 LESS 而不是 CSS 中?

最终的 HTML 将如下所示:(其中 9 将显示 4.5 颗星)

<div class="stars empty">
  <div class="stars filled_9">4.5</div>
</div>

最佳答案

就像资源链接一样简单:http://blog.thehippo.de/2012/04/programming/do-a-loop-with-less-css

这是资源中的代码示例:

更少的代码:

@iterations: 30;

// helper class, will never show up in resulting css
// will be called as long the index is above 0
.loopingClass (@index) when (@index > 0) {

    // create the actual css selector, example will result in
    // .myclass_30, .myclass_28, .... , .myclass_1
    (~".myclass_@{index}") {
        // your resulting css
        my-property: -@index px;
    }

    // next iteration
    .loopingClass(@index - 1);
}

// end the loop when index is 0
.loopingClass (0) {}

// "call" the loopingClass the first time with highest value
.loopingClass (@iterations);

生成的 CSS:

.myclass_30 {
  my-property: -30 px;
}
.myclass_29 {
  my-property: -29 px;
}

.......
.......
.......

.myclass_1 {
  my-property: .1 px;
}

关于html - 我怎样才能用 LESS 而不是直接的 CSS 构建一个灵活的评级小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11848401/

相关文章:

css - 实现 css 复选框在 Rails 应用程序中不起作用

javascript - 需求较少的常见 mixins

html - Angular:用户登录时隐藏元素

html - 需要一个表格以适应 div 中的全屏和另一个固定宽度的 div

javascript - Foreach循环-基于点击事件jquery隐藏/显示

html - 使用 CSS 将文本居中,在空白区域填充分隔线

css - 少编译错误

css - 奇怪的页脚行为

javascript - 无法让 .siblings() 在 jQuery 中工作

javascript - 如何在不使用 'div' 条件的情况下将数组值拆分并添加到不同的 "if"组件中?