【问题标题】:CSS animation restarts if I move the mouse when the container retracts. Can you avoid this?如果在容器缩回时移动鼠标,CSS 动画会重新启动。你能避免这种情况吗?
【发布时间】:2015-12-08 23:54:46
【问题描述】:

当我在元素内移动鼠标但光标(鼠标指针)始终在原始元素内时,我想保持动画持续到最后而不是重新启动。有可能吗?

我的代码是:Fiddle Demo

.container{
  height: 200px;
  width: 100px;
}
.conteiner li{
  display: inline-block; float: left;
  text-align: center;
  height: 100%; width: auto;
  background-color: white;
}
.conteiner li a{
  position: relative; display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 2em 0 2em;
  border: solid 1px black;
}

.conteiner li:HOVER{
  animation-name: menu_header_li;
  animation-duration: 5s;
  animation-timing-function: linear;
}

@keyframes menu_header_li {
    0%{
      transform: rotateY(0deg);
      background-color: white;
    }
    50%{
      transform: rotateY(90deg);
      background-color: red;
    }
    100%{
      transform: rotateY(0deg);
      background-color: white;
    }
}

如果我在元素上移动鼠标,动画会重新开始,我不明白为什么。

【问题讨论】:

  • 提前感谢大家
  • 您是指鼠标移动还是快速鼠标移入、移出、移入组合?如果是前者,那么我看不到任何重启。如果是后者,那么纯 CSS 是做不到的。
  • mouse-in mouse-out,但在开始的 100px 中,不在页面的任何部分...当我将鼠标 51px 移动到 50px 时限制为 50px,动画重新开始
  • 我没听懂,但你的问题听起来像是 stackoverflow.com/questions/31806649/… 的重复。仅当hover 开启时才会添加动画。当您不再悬停元素(鼠标移出)时,动画将不再适用,因此它会在您再次悬停时恢复到原始位置并重新启动。
  • 但实际上我总是在原始元素的悬停(鼠标进入)中。

标签: css css-animations css-transforms


【解决方案1】:

animation 在您将鼠标悬停在容器内然后移动鼠标以使鼠标指针仍在元素的原始边界内时重新启动,因为 transform: rotateY() 会在动画开始后更改元素的边界,甚至尽管您在元素的原始边界内移动鼠标,但它会重置动画(因为浏览器将其视为鼠标移出和鼠标移入)。

当您hover 靠近元素的边缘时,这一点非常明显。将元素悬停在边缘附近,让动画开始,不要移动鼠标,直到鼠标移动到元素的边界之外,然后再次移动它 - 这会导致动画重置/重新启动。

li 悬停在li 上时,可以通过在a 上添加background-colortransform 而不是li 来克服这个问题(如下面的sn-p 所示)。将animation 添加到li:hover 上的a 是有效的,因为li 的边界在动画期间不再改变,因此悬停始终处于启用状态。

.container {
  height: 200px;
  width: 100px;
}
.conteiner li {
  display: inline-block;
  float: left;
  text-align: center;
  height: 100%;
  width: auto;
}
.conteiner li a {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 2em 0 2em;
  border: solid 1px black;
  background-color: white;
}
.conteiner li:HOVER a {
  animation-name: menu_header_li;
  animation-duration: 5s;
  animation-timing-function: linear;
}
@keyframes menu_header_li {
  0% {
    transform: rotateY(0deg);
    background-color: white;
  }
  50% {
    transform: rotateY(90deg);
    background-color: red;
  }
  100% {
    transform: rotateY(0deg);
    background-color: white;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<ul class="conteiner">
  <li>
    <a>Element one </a> 
  </li>
  <li>
    <a>Element two </a>
  </li>
</ul>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 2013-04-09
    • 2021-11-17
    相关资源
    最近更新 更多