iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 6
1
自我挑戰組

關於我的佛系SCSS開發系列 第 6

鐵人賽06天Interpolation

今天還是想要富奸,滿滿星期一憂鬱,加上這週還要上6天的班真心的累

今天要來講插值的用法,使用 #{},裡面的內容會被 SCSS 編譯:

編譯前
@mixin corner-icon($name, $top-or-bottom, $left-or-right) {
  .icon-#{$name} {
    background-image: url('/icons/#{$name}.svg');
    position: absolute;
    #{$top-or-bottom}: 0;
    #{$left-or-right}: 0;
  }
}

@include corner-icon('mail', top, left);
編譯後
.icon-mail {
  background-image: url("/icons/mail.svg");
  position: absolute;
  top: 0;
  left: 0;
}

上面這功能主要是可以讓我們在想要替換所需要得值,不管是key跟value的地方,都可以插入設定值,如上面的範例我們再mixin設定了一個$top-or-bottom的變數,這邊可以說一下這個用法,我們在使用mixin加上這個變數,編譯完如果我們在top跟bottom選了top這個值,編譯出來就只會出現top選項,這樣的範例用來設定四個角落的絕對定位,可以說是復用性就更高,不過前提要這樣用之前,也要知道用這樣的方式。

官網看到一個蠻特別例子,就是unique-id()這個用法,這個可以產生一個隨機name的名稱

編譯前
@mixin inline-animation($duration) {
  $name: inline-#{unique-id()};

  @keyframes #{$name} {
    @content;
  }

  animation-name: $name;
  animation-duration: $duration;
  animation-iteration-count: infinite;
}

.pulse {
  @include inline-animation(2s) {
    from {
      background-color: yellow;
    }
    to {
      background-color: red;
    }
  }
}
編譯後
.pulse {
  -webkit-animation-name: inline-u201b5c31;
          animation-name: inline-u201b5c31;
  -webkit-animation-duration: 2s;
          animation-duration: 2s;
  -webkit-animation-iteration-count: infinite;
          animation-iteration-count: infinite;
}

@-webkit-keyframes inline-u201b5c31 {
  from {
    background-color: yellow;
  }
  to {
    background-color: red;
  }
}

雖然這個方法應該會蠻少用的,蠻特別這個也是我今天看官網的範例才知道,scss也有可以隨機產生這一筆亂數選項,一般用這種亂數資料通常都是為了避免命名衝突,或是當想不到怎樣命名名字,就可以這樣去做,比較節省所需要命名構想名字時間,二來可以避面衝突,不過這樣也是有缺點,因為是隨機產生,命名規則就會極度不知道意思,真的萬這東西變更幅度不是很高,在考慮這樣來使用會是比較好選擇。


上一篇
鐵人賽05天Parent Selector
下一篇
鐵人賽07天map
系列文
關於我的佛系SCSS開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言