【问题标题】:Sass looping through class names starting with numberSass 循环遍历以数字开头的类名
【发布时间】:2015-05-09 20:12:06
【问题描述】:

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

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

【问题讨论】:

    标签: sass compass-sass


    【解决方案1】:

    HTML5 现在可以使用数字开头的 ID 和类名,但 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="bmwwhite"] { background: 所以.css文件中的输出是错误的:/
    • 不,它不是因为输出应该是 .bmwwhite { background:.......} 而输出是这样的 [class="bmwwhite"] { background: .......}
    • 嗯,应该没问题,比如 [type="text"]。可以这样访问属性。
    【解决方案2】:

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

    在 CSS1 中,类名可以以数字(“.55ft”)开头,除非它是尺寸(“.55in”)。在 CSS2 中,此类类被解析为未知维度(以允许将来添加新单位)为了使“22ltr-porche”成为有效类,CSS2 要求将第一个数字转义“.\32 2ltr-porche”[22ltr-门廊]

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

    @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;
    }
    
    .\32 2ltr-porche {
      background: url(/img/cars/22ltr-porche.jpg) no-repeat;
    }
    
    .\33 0ltr-cossworth {
      background: url(/img/cars/30ltr-cossworth.jpg) no-repeat;
    }
    

    http://sassmeister.com/gist/e07d3fd4f67452412ad0

    【讨论】:

      猜你喜欢
      • 2019-11-08
      • 2019-02-03
      • 2018-03-15
      • 2017-04-16
      • 2014-07-22
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多