2

在我的 CSS 中,我必须创建引用“头发颜色”和“发型”的类

我写了一个 mixin 来帮助我的 CSS 写作更有效率:

@mixin hair($hair, $colour) {
    .hair-#{$colour} .#{$hair}  { 
background:image-url("xsppsfhair#{$hair}#{$colour}.svg") center top no-repeat, 
image-url("xsppsheadgrey.svg") center top no-repeat, 
image-url("xsppsbhair#{$hair}#{$colour}.svg") center top no-repeat;
}


}

@include hair(spikyboy, blonde);    
@include hair(curlyafroboy, blonde);    

这将产生以下 CSS

.hair-blonde .spikyboy {
  background: url('../images/xsppsfhairspikyboyblonde.svg?1348681869') center top no-repeat, url('../images/xsppsheadgrey.svg?1348834673') center top no-repeat, url('../images/xsppsbhairspikyboyblonde.svg?1348682005') center top no-repeat;
}

.hair-blonde .curlyafro {
  background: url('../images/xsppsfhaircurlyafroblonde.svg?1348681869') center top no-repeat, url('../images/xsppsheadgrey.svg?1348834673') center top no-repeat, url('../images/xsppsbhaircurlyafroblonde.svg?1348682005') center top no-repeat;
}

这很棒,但是由于我总共有 35 种头发颜色和发型组合,所以我最终还是有太多的@includes。

在这个页面上,它说 SASS 有一个 @each 可以用来循环列表。这里还有一个例子。但是,这两个示例都只显示循环 1 个列表。是否可以遍历两个列表?

我已经尝试了我的代码的许多变体,但似乎没有一个工作。我认为以下内容肯定会起作用,但我只是收到一条关于 $colour 未定义的错误消息。

$hairstyle: (red, blonde, ltbrown);
$haircolour: (red, blonde, ltbrown);

    @each $hair in $haircolour, $colour in $haircolour {
    .hair-#{$colour} .#{$hair}  {
background:image-url("xsppsfhair#{$hair}#{$colour}.svg") center top no-repeat, 
image-url("xsppsheadgrey.svg") center top no-repeat, 
image-url("xsppsbhair#{$hair}#{$colour}.svg") center top no-repeat;
    }

    .girl.hair-#{$colour} #eyelash {
        background: image-url("xsppseyelash#{$colour}.svg") center top no-repeat;
    }
}

有人可以给我一些关于我做错了什么的指示吗?

4

1 回答 1

5

你需要做的是在第一个循环中创建一个循环(我已经简化了一点,所以更容易看到):

@mixin style-matrix($colors, $styles) {
    @each $s in $styles {
        @each $c in $colors {
            .#{$s} .#{$c} {
                background:image-url("xsppsfhair-#{$s}-#{$c}.svg");
            }
        }
    }
}

$colors: blonde, brunette, auburn;
$styles: beehive, pixie, bob;
@include style-matrix($colors, $styles);

你得到这个输出:

.beehive .blonde {
  background: image-url("xsppsfhair-beehive-blonde.svg");
}

.beehive .brunette {
  background: image-url("xsppsfhair-beehive-brunette.svg");
}

.beehive .auburn {
  background: image-url("xsppsfhair-beehive-auburn.svg");
}

.pixie .blonde {
  background: image-url("xsppsfhair-pixie-blonde.svg");
}

.pixie .brunette {
  background: image-url("xsppsfhair-pixie-brunette.svg");
}

.pixie .auburn {
  background: image-url("xsppsfhair-pixie-auburn.svg");
}

.bob .blonde {
  background: image-url("xsppsfhair-bob-blonde.svg");
}

.bob .brunette {
  background: image-url("xsppsfhair-bob-brunette.svg");
}

.bob .auburn {
  background: image-url("xsppsfhair-bob-auburn.svg");
}
于 2012-09-28T20:20:22.300 回答