html - 如何循环遍历表中的所有 td 元素,添加与 sass 颜色映射不同的颜色?

标签 html css sass

我想遍历所有 <td>我的表的元素将每个元素与我在名为 $options-colours 的 sass 映射中设置的颜色相匹配。此刻我被绊倒了,因为只有前 3 种颜色因为新的 <tr> 而不断重复。每一次。我知道我需要增加 <tr> nth-of-typenth-child每次我的索引都可以被 3 整除但我不确定如何将它们拼凑在一起时,有人可以解释我如何才能做到这一点吗?

SCSS

 table {
  width: 100%;


    tr {
    @for $i from 1 through length($option-colours) {

      /*
      &:nth-child(#{$i}) {
        if $i % 3 == 0 increment?
      }
      */

      td {
            width: 33.3333%;
            height: 100px;
        &:nth-of-type(#{$i}) {
            background: nth($option-colours, $i);
        }
        }
    }
  }
}

代码笔: http://codepen.io/styler/pen/oCKfJ?editors=110

HTML

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
  <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
  <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
  <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

最佳答案

基本上,我创建了一些变量来跟踪我们应该为哪一行以及哪个单元格设置样式。在循环的三次迭代之后,单元格计数器重置为 1,行计数器递增。我不太确定组织像这样的大型 SASS 循环的最佳实践是什么,所以欢迎任何反馈。

http://codepen.io/sdsanders/pen/nchtb?editors=110

table {
  width: 100%;
  $row: 1;
  $cell: 1;

    tr {
    @for $i from 1 through length($option-colours) {

      &:nth-child(#{$row}) {
        td {
          &:nth-child(#{$cell}) {
            background: nth($option-colours, $i);
          }
          $cell: $cell + 1;
          @if $cell == 4 {
            $cell: 1;
            $row: $row +1;
          }
        } 
      }
    }

    td {
      width: 33.3333%;
      height: 100px;
    }
  }
}

相关的 CSS 输出如下所示:

table tr:nth-child(1) td:nth-child(1) {
  background: #fcfcfc;
}
table tr:nth-child(1) td:nth-child(2) {
  background: #ebebea;
}
table tr:nth-child(1) td:nth-child(3) {
  background: #d7d7d6;
}
table tr:nth-child(2) td:nth-child(1) {
  background: #c2c2c1;
}
...

关于html - 如何循环遍历表中的所有 td 元素,添加与 sass 颜色映射不同的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24614132/

相关文章:

javascript - 如何在 webpack 中使用 node-sass-asset-functions?

php - 用于传递 PHP 变量的 Javascript 语法

javascript - 带有内部链接的 Bootstrap 侧边菜单在点击时跳转

html - 我通过在内部有一个勾号的外部 div 制作了一个自定义复选框..现在没有应用事件类

html - CSS,从新网页开始,试图让导航栏位于中间,宽度为 95%(每边 2.5% 空闲)

javascript - 优化Angular Js电商元素

css - SASS 嵌套注释

javascript - 如何在扩展后台页面访问localStorage?

html - Easeljs,这是固定容器大小的推荐方法吗?

html - 如何根据主页设置自动表格宽度?