从动画结束处继续过渡

Continue Transition from where Animation Ended

看下面的按钮动画:

html {
  background: white;
  font-family: Arial;
}

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  transition-property: color, background, border-color;
  transition-duration: 0.3s;
}
.button:hover {
  color: #fff;
}
.button:hover ._background:after {
  transform: translateX(0);
  animation: fill-horizontal 0.3s linear 0s 1;
}
.button ._background {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: -1;
  overflow: hidden;
}
.button ._background:after {
  content: "";
  position: absolute;
  display: block;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #000;
  transform: translateX(100%);
  transition: transform .3s;
}

@keyframes fill-horizontal {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}
<a class="button" href="javascript:">
  <div class="_background"></div>
  Button
</a>

预期的动画是从左侧扫入 ._background:after 元素,然后向右扫出,如下所示:

  1. translateX(-100%)
  2. translateX(0) - 悬停
  3. translateX(100%) - 删除悬停

虽然当用户在 CSS 动画 (.3s) 期间悬停时动画按预期工作,但如果用户 'unhovers' 在 [=48] =]动画完成。

我希望 transitiontranslateX(100%)animation 完成的地方继续。这可能吗?

注意 - 我知道 div._background 元素不是必需的,它具有与此问题无关的附加功能。

为了避免这种不良影响,您可以不同地考虑相同的效果:

这是一个使用背景动画的想法,其中的诀窍是仅在尺寸改变后才改变位置。

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  background-image:linear-gradient(#000,#000);
  background-size:0% 100%;
  background-position:left;
  background-repeat:no-repeat;
  background-origin:border-box;
  transition:color 0.3s, background-size 0.3s, background-position 0s 0.3s;
}
.button:hover {
  color:#fff;
  background-size:100% 100%;
  background-position:right;
}
<div class="button">Some text</div>

使用此方法,您将有一个转换回来,以防您快速悬停。


强制动画完成的一个怪主意是考虑一个伪元素,它会使悬停区域更大,并确保您将悬停保持到结束:

.button {
  position: relative;
  display: inline-block;
  color: #000;
  border: 2px solid #000;
  padding: 10px 24px;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  text-decoration: none;
  background-image:linear-gradient(#000,#000);
  background-size:0% 100%;
  background-position:left;
  background-repeat:no-repeat;
  background-origin:border-box;
  transition:color 0.3s, background-size 0.3s, background-position 0s 0.3s;
}
.button:hover {
  color:#fff;
  background-size:100% 100%;
  background-position:right;
}

.button:hover:before {
  content:"";
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  z-index:99;
  animation:remove 0s 0.3s forwards;
}
@keyframes remove {
  to {
    top:100%;
  }
}
<div class="button">Some text</div>