Jquery 动画 css 滚动会导致抖动

Jquery animate css on scrolling causes jitter

EDIT: The problem was using javascript animations in stead of CSS transitions. The codepen now shows a working example where JS is only used to translate the elements and CSS is used to animate it!

我正在尝试实现我在该网站上看到的某种效果:https://draft.co.jp/en/projects/page/geechs

他们在具有固定高度(以生成滚动条)的正文元素中使用固定定位的主要部分。滚动后,它们按与 $(window).scrollTop() 的比例平移主元素内的所有元素。他们使用平滑这种效果的动画。

我一直在尝试重新创建这种效果,但我的代码在滚动几下后会产生抖动的体验。 (有关示例,请参见 https://codepen.io/blauwhelm/pen/LRorNA)。

似乎是生成大量动画(我在本例中通过 jquery 插件使用过渡来为翻译 属性 设置动画)导致了这个问题。我已经尝试使用节流来限制触发器的数量,但这并不能解决问题。

我的javascript:

$(document).ready(function() {

var $mainElement = $('.main__element');

function smoothScroller(e) {
    var scrollTop = $(window).scrollTop();  
    console.log('scroll trigger');
    $mainElement.stop(true, false).transition({y: -scrollTop}, 3000, "cubic-bezier(.19,0.88,0,.99)", function() {
        console.log('end animation');
    });
}

$(window).bind('scroll', smoothScroller);
});

不知何故 'end animation' 消息比 'scroll trigger' 多很多,我也不明白。

有人知道我该如何修复抖动动画吗?

谢谢!

他们为此大量使用 Greensock 的 GSAP,这是一个很棒的库,但更多的是企业解决方案和不错的学习曲线。

一个好的起点是查看 requestAnimationFrame 和节流方法(我在这个例子中使用了 lodash)。

使用 translateY(或 X 或 3d)代替 top

也有帮助

这是一个 JSBin 演示 HTML/CSS/JS,但这里是相关位:

JS

var ticking = false,
    item = document.querySelectorAll('.item');


// RAF
function update() {
  ticking = false; 
  item[0].style.transform = 'translateY('+window.scrollY+'px)';
}

function onScroll() {
  ticking = ticking || requestAnimationFrame(update);
}

window.addEventListener('scroll', onScroll, false);


// Scroll Throttle
function throttled_version() {
  item[1].style.transform = 'translateY('+window.scrollY+'px)';
}

window.addEventListener('scroll', _.throttle(throttled_version, 16), false);

给CSS一个transition也可以帮助流动性。在这种情况下只有 50 毫秒,因为它会反复触发。它有点模拟 velocity/momentum 效果