关于scss:使用scss制作按钮变亮变暗效果

3次阅读

共计 1589 个字符,预计需要花费 4 分钟才能阅读完成。

演示

  • 失常状态
  • 鼠标悬浮状态
  • 点击状态

演示为第一个区域(红色按钮)

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

这样就实现了按钮色彩加深减淡性能,来比照一下代码的行数:

咱们应用了 27 行 scss 代码就能编译出 71 行的 css 代码,这样大大增加了工作效率,并且色彩黯淡都是主动生成的。

如何将 scss 代码利用在 html 中

通过 scss 编译器将 scss 编译后失去 css 文件,应用 html 中的 link 标签就能够将该 css 文件加进 html 中。

正文完
 0