【问题标题】:Transitioning from animated to not animated in Chrome vs Firefox在 Chrome 和 Firefox 中从动画过渡到非动画
【发布时间】:2023-03-16 11:43:01
【问题描述】:

在启用过渡的元素中关闭动画时,Firefox 有一个很好的行为,它将元素带到任何位置并过渡回原始形式。

在 Chrome 中它只是跳跃而不转换。

为什么不一致?有没有办法在Chrome中复制而不用太多JS?

.wrapper {
  width: 400px;
  height: 200px;
}

.move {
  width: 100px;
  height: 100px;
  position: absolute;
  background-color: #f66;
  transition: 1s;
  cursor: pointer;
}

.move {
  animation: move 2s linear infinite;
}

.wrapper:hover .move {
  animation: none;
}

@keyframes move {
  50% {
    transform: translateX(200px);
  }
}
<div class="wrapper">
    <div class="move"></div>
</div>

【问题讨论】:

    标签: css animation css-transitions


    【解决方案1】:

    $(".spinny").bind("webkitAnimationEnd mozAnimationEnd animationEnd", function(){
      $(this).removeClass("spin")  
    })
    
    $(".spinny").hover(function(){
      $(this).addClass("spin");        
    })
    div {
      width: 100px;
      height: 100px;
      background-color: #f66;
      transition: 1s;
      cursor: pointer;
    }
    
    .spin {
      animation: spin 1s linear 1;
    }
    
    @keyframes spin {
      100% {
        transform: rotate(180deg);
      }
    }
    &lt;script src="https://code.jquery.com/jquery-3.1.0.js"&gt;&lt;/script&gt;&lt;div class="spinny"&gt;&lt;/div&gt;

    取自this answer,JS 可用于分别在悬停和动画完成时添加和删除类。此示例中使用了 jQuery,但对于功能而言,它不是必需的。

    编辑:现在没有 jQuery,只要通过记住状态并在每个动画结束后检查,它就会在悬停时播放动画。

    hover = 0;
    s = document.getElementById("spinny");
    s.addEventListener("animationend", function(){
      s.className = "";
      if (hover)
        setTimeout(function(){s.className = "spin"},0);
    })
    
    s.onmouseover = function(){
      s.className = "spin";
      hover = 1;
    }
    
    s.onmouseout = function(){
      hover = 0;
    }
    div {
      width: 100px;
      height: 100px;
      background-color: #f66;
      transition: 1s;
      cursor: pointer;
    }
    
    .spin {
      animation: spin 1s linear 1;
    }
    
    @keyframes spin {
      100% {
        transform: rotate(180deg);
      }
    }
    &lt;div id="spinny"&gt;&lt;/div&gt;

    【讨论】:

    • 在我原来的用例中,我实际上是在使用 JS 来切换动画类,为了简洁起见,在问题中省略了,但它无论如何都不起作用,我不确定你的示例应该回答我最初的问题,因为如果我将其更改为“无限”,它根本不起作用
    • @Faccion 在这种情况下,您可以保留 1 秒的动画,如果 1 秒后仍然悬停,您可以跟踪悬停状态以保持动画运行。
    • 我不明白,你能修改例子来说明你的意思吗?
    • 是的,我会的。 :)
    【解决方案2】:

    在你的变换旁边添加过渡

    .rotate {
      width: 200px;
      height: 200px;
      transform: rotate(0deg);
      transition: 0.5s ease all;
      background-color: #222;
      }
    .rotate:hover {
      transform: rotate(20deg);
      transition: 0.5s ease all;
      }

    这应该可以防止它跳跃。

    【讨论】:

    • 为简洁起见,我省略了问题中的前缀,但无论如何它都不适用于它们
    猜你喜欢
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 2023-03-20
    • 1970-01-01
    • 2013-03-01
    相关资源
    最近更新 更多