使用 :after 元素对按钮的悬停效果 - 当鼠标超出按钮尺寸时动画消失

Hover effect on button using :after element - Animate out when mouse is out of button dimensions

我定义了这个按钮动画: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 的区别在于我需要从按钮访问后元素。我试过这个:

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

并在按钮上使用它

animation: mymove-out .5s ease;

但这行不通。如何从关键帧访问后元素?

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

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>