当滚动回到顶部并移除 class 时跳转动画元素

Jumping animated element when scroll is back to the top and class is removed

我有一个关于动画的问题。 所以我制作了这个简单的动画,它应该在卷轴上激活并将徽标向左移动并稍微摆动一下。一切都很好,但是当我滚动回顶部时,元素跳转到其先前的位置并且看起来不自然。有什么方法可以使过渡更顺畅吗?

之前我只用这些属性做了一个简单的转换:

.sticky {
    transition: all .3s ease-in .1s;
    transform: translateX(-70px) rotate(25deg);
}

它没有跳回,但是当我添加关键帧并使动画更复杂时出现了问题。

#logo {
    max-width: 50px;
    display: inline-block;
    position: fixed;
    transition: all .3s ease-in-out .5s;
    -webkit-transform-origin: 50% 50% 0;        
    transform-origin: 50% 50% 0;
    font-size:50px;
}

.sticky {
    transition: all .3s ease-in-out .5s;    
    -webkit-animation: swinging 4.5s ease-in-out both;
    animation: swinging 4.5s ease-in-out both;
    animation-fill-mode: both;       
}

@keyframes swinging {
    0% {transform: translateX(0px) rotate(-10deg);}
    20% {transform: translateX(-70px) rotate(10deg);}
    40% {transform: translateX(-60px) rotate(-5deg);}
    60% {transform: translateX(-70px) rotate(5deg);}
    80% {transform: translateX(-70px) rotate(-2deg);}
    100% {transform: translateX(-70px) rotate(0deg);}
}

JavaScript

window.onscroll = function() {
    myFunction()
};
        
var header = document.getElementById("logo");
var sticky = header.offsetTop;
        
function myFunction() {
    if (window.pageYOffset > sticky) {        
        header.classList.add("sticky");
    } else {  
        header.classList.remove("sticky");
    }
}

我将非常感谢任何解决方案和帮助。这是一个简单的代码笔,或多或少地显示了这个问题:https://codepen.io/tonysnufkin/pen/jOVXbpP

一个解决方案是提供一个 'counter-animation',它使元素从 swinging 的最终位置回到初始位置。例如:

@keyframes unswing {
  0% {transform: translateX(-70px)} /* final position of swinging transform */
  100% {transform: translateX(0)} /* original position */
}

这会在初始页面加载时产生动画效果。如果这是不可取的,请考虑将动画附加到 class,您可以在删除 sticky.

时用 javascript 切换它

Updated Codepen