使用:after元素在按钮上悬停效果-鼠标超出按钮尺寸时动画

时间:2018-12-18 14:05:37

标签: html css sass pseudo-element keyframe

我已定义以下按钮动画:JSFIDDLE

代码也包含在此处:

HTML

<button>Hover to change color</button>

SCSS

$blue: #0084ff;
$blue-darker: darken($blue, 5);

@keyframes mymove {
    0% {width: 0%}
    100%  {width: 80%}
}

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
button {
  margin: auto;
  background-color: $blue;
  border: 1px solid $blue;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  cursor: pointer;
  position: relative;
   &:hover {
    &:after {
      content: "";
      position: absolute;
      bottom: 3px;
      width: 80%;
      height: 2px;
      background-color: white;
      left: 0;
      right: 0;
      margin: auto;
      animation-name: mymove;
      animation-duration: .5s;
     }
  }
}

这是一个简单的悬停动画。问题是当鼠标离开按钮时,:after元素消失。我想在鼠标离开时为:after元素设置动画吗? -你会怎么做?

我是否应该将关键帧修改为也包含相反的方向? 100%到0%?还是完全其他的东西?

编辑:

this question的区别在于,我需要从按钮访问after元素。我已经尝试过:

@keyframes mymove-out {
    from {&:after {
      width: 80%
      }}
    to  {&:after {
      width: 0
    }}
}

并在按钮上使用它

animation: mymove-out .5s ease;

但这不起作用。如何从关键帧访问after元素?

1 个答案:

答案 0 :(得分:2)

您可以使用背景颜色和过渡来简化代码:

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  border: 1px solid #0084ff;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  cursor: pointer;
  background:
   linear-gradient(#fff,#fff) 50% calc(100% - 3px) no-repeat,
   #0084ff;
  background-size:0% 2px;
  transition:.5s all;
   
}

button:hover {
  background-size:80% 2px;
}
<button>Hover to change color</button>