【问题标题】:Prevent all scrolling until a function triggers阻止所有滚动,直到函数触发
【发布时间】:2016-02-11 20:58:33
【问题描述】:

我正在尝试重新创建这种效果: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;  
    }

但如果我先禁用滚动,当用户尝试滚动时如何触发函数?

【问题讨论】:

  • document.onscroll = function(){ preventScroll();在你的 disableScroll 函数中,你必须有一个条件语句来加载你想要的东西。
  • 你能给我一个代码示例吗?例如,如果尝试滚动,我想隐藏“div”。它会是什么样子? (对不起,我不明白我会使用什么条件语句,所以看一个真实的例子会有所帮助)
  • document.getElementById("div").style.display = "none"; 这将隐藏 div。如果您想在滚动时执行此操作,可以将其放入 preventScroll 函数,该函数在我的最后评论中由 document.onscroll 在滚动时触发。
  • @ChrisFrank 谢谢。但是,如果我在 on scroll 函数周围执行“if var == true”语句,并在条件内将变量更改为 false,则函数将继续循环。这是为什么?如果变量更改为false,我想停止循环。这是一个 js 小提琴 - jsfiddle.net/beliy333/rnd8gun4
  • 解决方案:将条件放在'document.onscroll'中。所以一起:document.onscroll = function() { if( scrolled == false){ blogHeaderMagic() } }

标签: javascript jquery


【解决方案1】:

感谢@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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多