iT邦幫忙

DAY 29
7

30天掌握Sass語法系列 第 25

30天掌握Sass語法 - (29) @for+random()創造無限可能

for迴圈不論是在哪個程式語言上都非常的常見,
這一次則是介紹Sass @for的運用方法。

Yes
我們先來一個簡單的範例

@for $i from 1 through 3
  .font-#{$i}
    font-size: 2em * $i

上面用白話文講的意思是,
@for會跑三次迴圈,
$i的變數帶入變數1、2、3到下面Class與CSS設定。
最終產出來的code會變成:

.font-1 {font-size: 2em;}
.font-2 {font-size: 4em;}
.font-3 {font-size: 6em;}

應用面也可以拿它來建立Grid,

$grid-number:12
@for $i from 1 through $grid-number
  .grid-#{$i}
    width: $i*80px

也可以將外部變數依序帶進去,
下面的範例我用了
1.length()
用來去計算變數總數量
2.invert(color)
將顏色替換成反相色,
網頁設計師也可去思考該如何透過Sass所提供的color功能,
讓他自動產生出其色碼出來:

$box-bg: blue,red,pink,orange
$box-len: length($box-bg)
.color-total
  color: $box-len
@for $i from 1 through $box-len
  .#{nth($box-bg,$i)}
    color: nth($box-bg,$i)
    background: invert(nth($box-bg,$i))

編譯出來的CSS就會變成:

.color-total {
  color: 4;
}
.blue {
  color: blue;
  background: yellow;
}
.red {
  color: red;
  background: cyan;
}
.pink {
  color: pink;
  background: #003f34;
}
.orange {
  color: orange;
  background: #005aff;
}

random()
這個Compass新功能,
是我不經意到codepen的一篇文章瀏覽到的,
文章連結:http://blog.codepen.io/2013/08/26/random-function-in-sass/
簡單的講如果我寫Sass為height: random(300) + px,
那我的高度編譯出CSS後就會隨機跑一個數值出來,

所以任何只要有寫到數值的地方,
譬如透明度、CSS3動畫、box大小、
你都可以用random()的地方大大增加它的變化性!
這變數也可以讓網頁設計師在發想動畫時,
可以藉由此功能大大地提昇開發效率。

舉例來說,
我有一個背景要做成有很多圓形圖案飛過的特效,
所以我必須先思考其下設定:
(1)100個圓形的背景顏色都需不一樣
(2)每個圓形的移動速度都要不一樣

如果是用傳統CSS,可想而知一定會寫到想崩潰,
但如果是用emmet加上Sass @for+random()的話,
就能夠輕易地做到:

//$boxes是圓形數量,.box為設定一外框,當我滑鼠滑過去時,裡面所有div都會向左移動2000px。
$boxes: 100
.box
  height: 1000px
  width: 1000px
  position: relative
  +transition(all 1s)
  &:hover div
    margin-left: 2000px
//在background與cubic-bezier移動加速度上設定了random(),讓他隨機跑顏色與速度曲線出來。
//在left與bottom上隨機定位各圓形的位置
@for $i from 1 through $boxes
  .for-#{$i}
    color: #000
    height: 50px
    width: 50px
    +box-shadow(5px 5px #000)
    background: rgb(random(255),random(255),random(255))
    +border-radius(50px)
    position: absolute
    left: random(1000) - 100 + px
    bottom: random(1000) - 100 + px
    +transition(all 3s cubic-bezier(#{random(0.999)}, #{random(0.999)}, #{random(0.999)}, #{random(0.999)}))


實際效果Demo:http://codepen.io/liao/pen/uHehF

從上述@for的介紹,
就可看出其設計潛力出來,
以前在做動畫有諸多不便的地方,
透過Sass&Compass內建的功能都可輕易地實踐出來,
讓設計的思維與巧思都不會因為HTML與CSS需要一次設定太多東西而怯步,
如果你對做網頁動畫也有強烈的興趣,那就不容錯過random()的功能!
於此也附上影片流程提供各位參考:
Yes


上一篇
30天掌握Sass語法 - (28)Compass圖片合併功能(CSS Sprite)
下一篇
30天掌握Sass語法 - (30)inline-image()與Livereload介紹
系列文
30天掌握Sass語法41
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言