scss list @each的使用以及样式优化

197 阅读1分钟
1.@each的使用

最初代码:

<style lang="scss" scoped>
    .ranking-order1 {
      @include backgroundImage(104px, 80px, $imgBaseUrl + '/1.png');
    }

    .ranking-order2 {
      @include backgroundImage(104px, 80px, $imgBaseUrl + '/2.png');
    }
    .ranking-order3 {
      @include backgroundImage(104px, 80px, $imgBaseUrl + '/3.png');
    }
</style>

修改后

<style lang="scss" scoped>
    $list: 1, 2, 3;
    @each $item in $list {
      .ranking-order#{$item} {
        @include backgroundImage(104px, 80px, $imgBaseUrl + '/#{$item}.png');
      }
    }
</style>

除这个之外,还有两个样式优化:

2.当使用keyframes时,相同的变化,可以写到一起
 @keyframes levelUpAnimate {
    0%, 12%, 24%{
      transform: translate(-8px, -4px)
    }
    3%, 15%, 27%{
      transform: translate(11px, 5px)
    }
    6%, 18%, 30%{
      transform: translate(-17px, -3px)
    }
    9%, 21%, 33%{
      transform: translate(15px, 6px)
    }
    40%{
      opacity: 1;
      transform: translate(0, 0) scale(1);
    }
    50%, 70%{
      opacity: 0;
      transform: translate(0, 0) scale(.2);
    }
    80%{
      opacity: 1;
      transform: translate(0, 0) scale(1.1);
    }
    100%{
      opacity: 1;
      transform: translate(0, 0) scale(1);
    }
  }
3可以将一些公共的样式封装,include引入

公共样式文件

// 字体样式设置(字体大小、字体颜色、行高、字粗)
@mixin fontSet($size, $color, $lineHeight: normal, $weight: 400) {
    font-size: $size;
    color:$color;
    font-weight: $weight;
    line-height: $lineHeight;
}

scope里面的样式

 @include fontSet(26px, #dddddd, 104px);
4可以定义公共路径
  $imgBaseUrl: $imageFolderPath + '/starMine/components/mainMine';
  &.staitc{
   background: url($imgBaseUrl + '/dig_icon.png') no-repeat center/cover
  }
  &.prop2{
     background: url($imgBaseUrl + '/prop/prop2.png') no-repeat center/contain;
  }