将window.requestAnimationFrame与Onscroll事件一起使用

时间:2020-06-26 18:59:17

标签: javascript html css

一旦用户通过使用translateY(创建背景附件:固定的效果)滚动到可见的位置,下面的代码将使具有背景图像的绝对定位元素跟随屏幕。它可以正常工作,但是有点断断续续/不稳定/不完全平滑(我添加了will-change:转换为使其更平滑但不完全平滑的元素)。

window.onscroll = function (e) {

  var mzParallax = document.getElementById('MZBGimg4');
  var windowHeight = window.screen.height;
  var bottomScrollPosition = window.pageYOffset + windowHeight;
  var mzElementDistance = document.getElementsByClassName('CompanyContainer4')[0].offsetTop;
  var ParallaxPosition = bottomScrollPosition - mzElementDistance - windowHeight;
    
    if (bottomScrollPosition >= mzElementDistance) {
        mzParallax.style.transform = 'translate(-50%, ' + ParallaxPosition + 'px)';
    }
    else {
        mzParallax.style.transform = 'translate(-50%, 0)';      
    }
}

我一直在寻找潜在的解决方案,但是我对Javascript还是很陌生,所以我对其中的许多内容不甚了解。不过,我确实做到了 window.requestAnimationFrame 。我尝试了这段代码,但是看起来似乎只在加载一次时触发,而不是滚动,但是很容易丢失一些明显的东西:

  var requestAnimationFrame = window.requestAnimationFrame
    || window.webkitRequestAnimationFrame
    || window.mozRequestAnimationFrame
    || window.msRequestAnimationFrame
    || window.oRequestAnimationFrame
    || function(callback){ setTimeout(callback, 0) };
  var mzParallax = document.getElementById('MZBGimg4');
  var windowHeight = window.screen.height;
  var bottomScrollPosition = window.pageYOffset + windowHeight;
  var mzElementDistance = document.getElementsByClassName('CompanyContainer4')[0].offsetTop;
  var ParallaxPosition = bottomScrollPosition - mzElementDistance - windowHeight;

window.addEventListener('scroll', function() {
    requestAnimationFrame(Parallax);
});

function Parallax(e) {
    if (bottomScrollPosition >= mzElementDistance) {
        mzParallax.style.transform = 'translate(-50%, ' + ParallaxPosition + 'px)';
    }
    else {
        mzParallax.style.transform = 'translate(-50%, 0)';      
    }
}

此代码是否向任何人透露我缺少或做错的事情?如果不够的话,我也许可以提供更多代码。

谢谢!

0 个答案:

没有答案