且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有没有办法在滚动事件之前采取行动?

更新时间:2022-10-14 22:35:11

您需要处理以下事件:


  • 滚轮(当您使用鼠标滚轮时)
  • mousedown(当你点击文档的滚动条滚动时)
  • / li>


如果您需要停止滚动,则只需添加preventDefault即可。



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



片段:



$(document).on('wheel mousedown keydown',function(e){if(e.type == 'e'type =='keydown'&&((e.ctrlKey&&(e.keyCode == 36 || e。其中== 35))||(!e.ctrlKey&&(e.keyCode == 33 || e.which == 34 || e.which == 38 || e.which == 40)) )){console.log(e.type +'event'); //你可能想要防止滚动: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&GT;&LT; /脚本&GT;


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.

You need to handle the following events:

  • wheel (when you use the mouse wheel)
  • mousedown (when you click on the scroll bar of the doc to scroll)
  • keydown (ctrl+home, ctrl+hend, down-up arrow, pgdown and pgup: keyboard scrolling)

If you need to stop the scrolling at all it's enough you add the preventDefault.

These are fired before scroll event.

The snippet:

$(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>