css实现炫酷hover效果

911 阅读3分钟

本篇文章带大家实现三种hover的效果,原理都是通过伪元素来实现,所以只要巧用伪元素,大部分的效果都是可以实现的。

  • 边框环绕
  • 反差颜色进度
  • 展示菜单

border-around.gif contrast.gif frame-content.gif

边框环绕

border-around.gif

这种 hover 的特效很常见,第一眼应该可以很明确的感知到肯定跟 border 属性有关,猜对了!

首先我们来解剖一下这个特效的动作,边框的渲染顺序是 top => right => bottom => left

我们可以通过定义 beforeafter 伪元素,before定位在左上角, after定位在右下角,在hover的时候就可以通过动画来控制伪元素的宽高以达到效果

直接实践,我们先设置两个伪元素在边角位置

<p class="border-around">边框环绕</p>

.border-around::before,
.border-around::after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  border: 2px solid #000;
}
.border-around::before {
  top: 0;
  left: 0;
}
.border-around::after {
  bottom: 0;
  right: 0;
}

效果中的黑点就是伪元素的位置,设置了黑色边框以便大家看到,现在我们需要设置hover的效果,接下来就是设置hover的时候再通过动画按顺序将伪元素的宽高变成100%

.border-around::before,
.border-around::after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  border: 2px solid transparent;
  box-sizing: border-box;
}
.border-around::before {
  top: 0;
  left: 0;
}
.border-around::after {
  bottom: 0;
  right: 0;
}
.border-around:hover::before,
.border-around:hover::after {
  width: 100%;
  height: 100%;
}

.border-around:hover::before {
  border-top: 2px solid blue;
  border-right: 2px solid blue;
  transition: width 0.3s ease-out, height 0.3s ease-out 0.3s;
}
.border-around:hover::after {
  border-bottom: 2px solid blue;
  border-left: 2px solid blue;
  transition: border-color 0s ease-out 0.6s, width 0.3s ease-out 0.6s, height 0.3s ease-out 0.9s;
}

动画解析:在hover的时候先执行 before 伪元素的 width 的动画时长为0.3s,然后执行 height的动画时长为0.3s并延迟0.3s执行,就实现了 bordertop => right

同理 after 伪元素实现 bottom => left 的原理也是如此,有些人不理解border-color 0s ease-out 0.6s这里的动画,这里是为了在0.6s之后才出现after 伪元素的 border

反差颜色进度

contrast.gif

这个原理挺简单的主要就是 mix-blend-mode属性,感兴趣的同学可以去了解一下

<div class="contrast">反差颜色进度</div>

.contrast {
  display: inline-block;
  position: relative;
  background: #fff;
  color: #000;
  padding: 3px 12px;
  border: 1px solid #000;
  box-sizing: border-box;
  cursor: pointer;
}
.contrast::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 0;
  background: #fff;
  mix-blend-mode: difference;
  transition: all 1s ease-in-out;
}
.contrast:hover::after {
  width: 100%;
}

展示菜单

frame-content.gif

这个 hover 效果原理也是通过定位beforeafter 伪元素,分别在对角两侧,在鼠标未悬浮的时候将其透明然后位置是在里面平移出来

<div class="active-menu">选中菜单</div>

.active-menu::before,
.active-menu::after {
  content: '';
  position: absolute;
  width: 10px;
  height: 10px;
  opacity: 0;
  transition: all .6s ease;
}
.active-menu::before {
  bottom: 0;
  left: 0;
  transform: translate(100%, -50%);
  border-left: 2px solid #000;
  border-bottom: 2px solid #000;
}
.active-menu::after {
  right: 0;
  top: 0;
  transform: translate(-100%, 50%);
  border-top: 2px solid #000;
  border-right: 2px solid #000;
}
.active-menu:hover::before,
.active-menu:hover::after {
  transform: translate(0, 0);
  opacity: 1;
}