Is there a way to act before the scroll event?

时间:2016-10-20 20:11:15

标签: javascript jquery html css

So I discovered that

e.preventDefault()
e.stopPropagation();
return false;

Do nothing if the triggering event is a scroll,

However, is there anyway to 'beat' the scroll event in firing order?

body{
   width: 100%;
   height: 2000px;
}

$(document).on('scroll', function(e){
    $('body').css('overflow','hidden');
    setTimeout(function(){
       $('body').css('overflow','auto')
    },100)
});

The above code does not work, the event trigger fires but the document scrolls before overflow is hidden every single time. however if the overflow can be hidden before the event propagates then this would work.

Is this possible?

I'm not interested in just preventing scrolling, I actually have element moving position on a scroll event. Things aren't as noticeable in Firefox, however in chrome(and especialy IE), the move clearly happens after the scroll.

2 个答案:

答案 0 :(得分:1)

您需要处理以下事件:

  • 轮(当您使用鼠标滚轮时)
  • mousedown(当您单击要滚动的文档的滚动条时)
  • keydown(ctrl + home,ctrl + hend,down-up arrow,pgdown和pgup:键盘滚动)

如果您需要完全停止滚动,则添加preventDefault。

这些在滚动事件之前被触发。

摘录:



$(document).on('wheel mousedown keydown', function(e){
  if (e.type == 'wheel' || e.target.tagName == 'HTML' ||
      (e.type == 'keydown' && ((e.ctrlKey && (e.keyCode  == 36 || e.which == 35)) ||
                               (!e.ctrlKey && (e.keyCode  == 33 || e.which == 34 || e.which == 38|| e.which == 40))))
     ) {
    console.log(e.type + ' event');

    //you may want to prevent the scroll: add next line + return;
    //
    //e.preventDefault();
    $('body').css('overflow','hidden');
    setTimeout(function(){
      $('body').css('overflow','auto')
    },100)
  }
});

body{
  width: 100%;
  height: 2000px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我不确定我完全理解你的问题。您想在用户尝试滚动时禁用滚动吗?默认情况下,当我们只滚动鼠标滚轮时,浏览器似乎无论如何都会滚动114px。因此,无论我们做什么,它都会在mousewheel事件上滚动窗口。如果您想要禁止滚动,可以强制窗口使用$(window).scrollTop(myvalue)保持在特定的滚动位置。 E.g:

var currpos = $(window).scrollTop();
$(document).on('scroll', function(e){
    $('body').css('overflow','hidden');
    $(window).scrollTop(currpos);
    setTimeout(function(){
       $('body').css('overflow','auto')
    },100)
});