動態

詳情 返回 返回

使用scss製作按鈕變亮變暗效果 - 動態 詳情

演示

  • 正常狀態
    image.png
  • 鼠標懸浮狀態
    image.png
  • 點擊狀態
    image.png

演示為第一個區域(紅色按鈕)

front

在我們進行前端開發時,如果用純CSS實現這種鼠標懸浮時變深,點擊變淺很容易(:hover,:focus),但是數量一多,寫起來就非常噁心,所以我們可以用scss來完成這種效果。

scss-codes

.all{ //通用屬性
    width: 60px;
    height: 60px;
    margin: 20px;
    display: inline-block;
    border-radius: 10px;
    outline: none;   //禁止點擊時出現外邊
    border: none;    //禁止邊框
}
$list: rgb(255, 0, 0),rgb(255, 217, 0),rgb(0, 38, 255),rgb(0, 255, 255); //顏色數組,可以使用HEX,rgb,這裏最好不要用rgba
@for $i from 1 through 4{ //through後的數字是要創建div的個數
    .ml-#{$i}{ //如ml-1,ml-2,ml-3
        @extend .all; //繼承.all
        font-size: 10px * $i;
        background-color: nth($list,$i); //設置默認背景顏色,此處會調用顏色數組中對應的顏色
        color: white;
        transition: all 0.3s; //添加動畫效果
        $color: nth($list,$i); //將對應顏色創建變量$color,避免出現重複語句
        &:hover{ //鼠標懸浮
            background: darken($color,20%); //亮度減淡20%
        }
        &:active{ //鼠標點擊
            background: lighten($color,20%); //亮度提升20%
        }
    }
}

css-codes

編譯後的結果:

.all, .ml-1, .ml-2, .ml-3, .ml-4 {
  width: 60px;
  height: 60px;
  margin: 20px;
  display: inline-block;
  border-radius: 10px;
  outline: none;
  border: none;
}

.ml-1 {
  font-size: 10px;
  background-color: red;
  color: white;
  transition: all 0.3s;
}

.ml-1:hover {
  background: #990000;
}

.ml-1:active {
  background: #ff6666;
}

.ml-2 {
  font-size: 20px;
  background-color: #ffd900;
  color: white;
  transition: all 0.3s;
}

.ml-2:hover {
  background: #998200;
}

.ml-2:active {
  background: #ffe866;
}

.ml-3 {
  font-size: 30px;
  background-color: #0026ff;
  color: white;
  transition: all 0.3s;
}

.ml-3:hover {
  background: #001799;
}

.ml-3:active {
  background: #667dff;
}

.ml-4 {
  font-size: 40px;
  background-color: cyan;
  color: white;
  transition: all 0.3s;
}

.ml-4:hover {
  background: #009999;
}

.ml-4:active {
  background: #66ffff;
}

end

這樣就實現了按鈕顏色加深減淡功能,來對比一下代碼的行數:
image.png
我們使用了27行scss代碼就能編譯出71行的css代碼,這樣大大增加了工作效率,並且顏色暗淡都是自動生成的。

如何將scss代碼應用在html中

通過scss編譯器將scss編譯後得到css文件,使用html中的link標籤就可以將該css文件加進html中。

Add a new 評論

Some HTML is okay.