Sass 遍历 class 个以数字开头的名称

Sass looping through class names starting with number

我正在遍历 sass 中的名称列表,当 sass 到达 class 名称以数字开头的点时,它似乎中断了。事实上,当我注释掉以数值开头的 class 名称时,sass 编译工作正常。那就是说我无法重命名 class 名称。我怎样才能让它发挥作用?下面是我正在尝试的代码:

@each $car in
  bmwwhite
  hondared
  //22ltr-porche
  //30ltr-cossworth
 {
  .#{$car} {
    background:url(/img/cars/#{$car}.jpg) no-repeat 
  }
 }

HTML5 现在可以使用起始 ID 和 class 带数字的名称,但 CSS 不是 (Here's some info about all this).

Sass 可能不允许您创建无效的 CSS 选择器,例如 .22ltr-porche 这样才有意义。虽然有办法绕过它。

你可以试试这个:

@each $car in
  bmwwhite
  hondared
  22ltr-porche
  30ltr-cossworth
 {
  [class="#{$car}"] {
    background:url(/img/cars/#{$car}.jpg) no-repeat 
  }
 }

这将创建一个看起来像这样的选择器 [class="22ltr-porche"]Sass is OK with that.

像这样的不合格属性选择器往往很慢。您应该尝试将属性选择器与更具体的东西结合起来。这是 example plunkr.

您尝试生成的 class 无效。 运行 它通过验证器会给出这个错误:

In CSS1, a class name could start with a digit (".55ft"), unless it was a dimension (".55in"). In CSS2, such classes are parsed as unknown dimensions (to allow for future additions of new units) To make "22ltr-porche" a valid class, CSS2 requires the first digit to be escaped ". 2ltr-porche" [22ltr-porche]

所以,我们需要转义前导数字,就像它说的那样:

@function escape_leading_numbers($s) {
  $first-char: str_slice(#{$s}, 0, 1);
  $found: index('1' '2' '3' '4' '5' '6' '7' '8' '9' '0', $first-char);
  @return if($found, unquote(str-insert(str-slice(#{$s}, 2), "\3#{$first-char} ", 1)), $s);
}

$name: '007';

.#{escape_leading_numbers($name)} {
  color: red;
}

@each $car in
  bmwwhite
  hondared
  22ltr-porche
  30ltr-cossworth
 {
  .#{escape_leading_numbers($car)} {
    background:url(/img/cars/#{$car}.jpg) no-repeat
  }
 }

输出:

.bmwwhite {
  background: url(/img/cars/bmwwhite.jpg) no-repeat;
}

.hondared {
  background: url(/img/cars/hondared.jpg) no-repeat;
}

. 2ltr-porche {
  background: url(/img/cars/22ltr-porche.jpg) no-repeat;
}

. 0ltr-cossworth {
  background: url(/img/cars/30ltr-cossworth.jpg) no-repeat;
}

http://sassmeister.com/gist/e07d3fd4f67452412ad0