在函数触发之前阻止所有滚动

时间:2015-11-10 20:41:18

标签: javascript jquery

我正在尝试重新创建此效果:http://www.jam3.com/work/#mobilemusicvideo

在顶部图像的动画完成之前,将禁用页面的所有滚动。但是,当用户尝试滚动时,会触发该图像动画。

怎么能创造这个?

我可以使用此功能阻止滚动:

function disableScroll() {
  if (window.addEventListener) // older FF
      window.addEventListener('DOMMouseScroll', preventDefault, false);
  window.onwheel = preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
  window.ontouchmove  = preventDefault; // mobile
  document.onkeydown  = preventDefaultForScrollKeys;
}

使用此功能重新启用它:

 enter code herefunction enableScroll() {
        if (window.removeEventListener)
            window.removeEventListener('DOMMouseScroll', preventDefault, false);
        window.onmousewheel = document.onmousewheel = null; 
        window.onwheel = null; 
        window.ontouchmove = null;  
        document.onkeydown = null;  
    }

但是,如果我首先禁用滚动,当用户尝试滚动时如何触发功能?

1 个答案:

答案 0 :(得分:0)

感谢@ChrisFrank的提示。您可以在滚动尝试时触发该功能并禁用滚动,如下所示:

document.onscroll = function() {
    if( scrolled == false){
        yourCustomFunction();
    }
}

在我的自定义函数中,我禁用了滚动(我得到了这个函数here),做了我的动画并将变量更改为true:

function blogHeaderMagic() {
     //to re-position scroll to 0 (in my case this was useful)
     $('body,html').animate({scrollTop: 0 }, 1);

     //disable scroll function
     disableScroll()

     //my animation and on a callback you'll see I call allowScroll function to allow scroll normally once animation completes
     TweenMax.to("#post-hero-media-wrapper", 1, {height:54, opacity: .4, width: mainWidth, ease: Power3. easeInOut, y: 0, onComplete: allowScroll });
     scrolled = true
}