css animation返回第一帧会有明显的移动,如何解决?

同一个滚动效果,用js的requestAnimationFrame控制返回初始态非常自然,没有痕迹,但是用css animation控制,则回到第一帧,会有明显的下移动作,这个问题能否解决?

在线demo

关键代码如下:
css animation版本:

.m-tb-scroll tbody{display:block}
.m-tb-scroll tbody.scroll{height:850px;overflow:hidden;overflow-y:scroll}
.m-tb-scroll thead,.m-tb-scroll tbody tr{display:table;width:100%;table-layout:fixed}
.m-tb-scroll tbody.ani{
    animation:scroll var(--scrollDuration) linear both infinite;
    animation-play-state:var(--scrollPause)
}
@keyframes scroll{
    0%{transform:translateY(var(--scrollTopDebounce))}
    100%{transform:translateY(var(--scrollY))}
}
if(scroll > 10){
    scroll += this.bottomDebounce;
    target.classList.remove('scroll');
    target.classList.add('ani');

    console.log('scroll: ', scroll);
    
    let scrollDuration = scroll/60;
    document.body.style.setProperty('--scrollDuration', `${scrollDuration}s`);
    document.body.style.setProperty('--scrollY', `-${scroll}px`);
    document.body.style.setProperty('--scrollTopDebounce', `${this.topDebounce}px`);
    this.setAnimationPause();
}
else{
    target.classList.remove('ani');
}

js版本

if (scroll > 10) {
    target.classList.remove('scroll');

    requestAnimationFrame(animate);

    let step = 0;
    function animate() {
        if (self.stop) return;
        console.log('puase: ', self.pause);
        if(!self.pause){
            if (step >= scroll) {
                step = 0;
            }
            else {
                step += 1;
            }
            target.style.transform = `translateY(-${step}px)`
        }
        requestAnimationFrame(animate);
    }
} else {
    self.stop = true;
    target.style.transform = `translateY(0)`
}
阅读 1.9k
1 个回答

https://codepen.io/lie5860/pe...
观察后得到 并不是一个明显的下移动作,而是两个方法的位移不相同 且js的距离刚好是一行的距离。
我这边先是把scroll固定为一行的距离(仅测试用)。这样刚好第二行的文字在跳回去的时候会刚好覆盖第一行的字 这样会显得丝滑。
然后移除了scroll += this.bottomDebounce; 不太懂为啥要修改滚动距离。如果距离不同的话那效果肯定也是不同的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题