sass 字符串拼接

$imgName: 'aa' 'bb' 'cc'
$imgPre: '../img/'
@for $i from 1 through 3
  .cate-#{$i} .imgw
    background: url(#{$imgPre}nth($imgName,$i)) no-repeat center

想要在url里拼出 ‘../img/aa’ '../img/bb'
语法好像有点不对,求解!

阅读 11.9k
2 个回答

还是直接看代码吧:

.SCSS格式

$imgName: aa, bb ,cc;
%bgr{
    background-repeat: no-repeat;
    background-position: center center;
}
@for $i from 1 through 3{
  .cate-#{nth($imgName, $i)} .imgw{
        @extend %bgr;
        background-image: url(../img/#{nth($imgName, $i)}.jpg);
        span{
            
        }
    }
}

被编译为:

.cate-aa .imgw, .cate-bb .imgw, .cate-cc .imgw {
  background-repeat: no-repeat;
  background-position: center center;
}
.cate-aa .imgw {
  background-image: url(../img/aa.jpg);
}
.cate-bb .imgw {
  background-image: url(../img/bb.jpg);
}
.cate-cc .imgw {
  background-image: url(../img/cc.jpg);
}

.SASS格式

$imgName: aa, bb, cc

%bgr
  background-repeat: no-repeat
  background-position: center center

@for $i from 1 through 3
  .cate-#{nth($imgName, $i)} .imgw
    @extend %bgr

    background-image: url(../img/#{nth($imgName, $i)}.jpg)

    span

被编译为:

.cate-aa .imgw, .cate-bb .imgw, .cate-cc .imgw {
  background-repeat: no-repeat;
  background-position: center center;
}
.cate-aa .imgw {
  background-image: url(../img/aa.jpg);
}
.cate-bb .imgw {
  background-image: url(../img/bb.jpg);
}
.cate-cc .imgw {
  background-image: url(../img/cc.jpg);
}

这么写就行了:

 background: url('#{$imgPre}#{nth($imgName,$i)}') no-repeat center;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进