Sass基礎學習No.7-@for迴圈結合random()隨機省時間

@for用途

@for就是迴圈的意思,會從設定的數值範圍第一個數開始一個接一個的帶入數字。

1
2
3
@for $x from 2 to 4
.items-#{$x}
font-size: 16px * $x
1
2
3
4
5
6
7
8
/*編譯結果CSS*/
.items-2 {
font-size: 32px;
}

.items-3 {
font-size: 48px;
}

@for迴圈寫法

分成2種

  • @for $變數名 from [start數字] to [end數字],顯示結果如上方程式碼,會將設定的數字從[start數字]開始一個一個帶入,帶到[end數字]前1個數字(不含[end數字])。

    1
    2
    3
    @for $變數名 from start數字 **to** end數字 
    .items-#{$變數名}
    font-size: 16px * $變數名
  • @for $變數名 from [start數字] through [end數字],顯示結果如下方程式碼,會將設定的數字從[start數字]開始一個一個帶入,帶到end數字

    1
    2
    3
    @for $x from 2 through 4
    .items-#{$x}
    font-size: 16px * $x
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    /*編譯結果CSS*/
    .items-2 {
    font-size: 32px;
    }

    .items-3 {
    font-size: 48px;
    }

    .items-4 {
    font-size: 64px;
    }

迴圈結合random可以呈現怎麼樣的效果

以動畫效果為例,呈現每個區塊隨機的消失及出現,如何隨機呢?透過random(random數字),來取得每一次電腦從1-random數字之間的某個值。

先寫下動畫效果,並將動畫效果帶入每個CSS選取器中。

1
2
3
4
5
6
7
8
9
10
11
12
13
//動畫效果樣式設計
@keyframes circleOpacity
0%
opacity: 1
100%
opacity: 0

@for $i from 1 through 3
.circle-#{$i}
width: 100px
height: 100px
background: red
animation: circleOpacity #{random(5)}s ease-in-out #{random(2)*0.9}s infinite alternate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*編譯結果CSS*/
@keyframes circleOpacity {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.circle-1 {
width: 100px;
height: 100px;
background: red;
animation: circleOpacity 2s ease-in-out 0.9s infinite alternate;
}

.circle-2 {
width: 100px;
height: 100px;
background: red;
animation: circleOpacity 1s ease-in-out 1.8s infinite alternate;
}

.circle-3 {
width: 100px;
height: 100px;
background: red;
animation: circleOpacity 5s ease-in-out 1.8s infinite alternate;
}

可以看到編譯完之後每個有設定的random(random數字)的值都不太一樣。

有關更多@for或random()的介紹可以參考
廖洧杰的@for+random()創造無限可能
Robin Rendle的Random Numbers in CSS