Catch scrolling event on overflow:hidden element

后端 未结 4 1725
醉话见心
醉话见心 2020-12-01 13:53

Any insights on how to catch a scrolling event on a element that has overflow:hidden? I would like to scroll in a column without showing a scrollbar to the user.

相关标签:
4条回答
  • 2020-12-01 14:28
    $("div").on('wheel', function (e) {
            if (e.originalEvent.deltaY < 0) {
            console.log("Scroll up");
        } else {
            console.log("Scroll down");
        }
    });
    

    This did the trick for me. JSFiddle

    StackFiddle:

    $("div").on('wheel', function(e) {
      if (e.originalEvent.deltaY < 0) {
        console.log("Scroll up");
      } else {
        console.log("Scroll down");
      }
    });
    div {
      height: 50px;
      width: 300px;
      background-color: black;
      overflow: hidden;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div></div>

    0 讨论(0)
  • 2020-12-01 14:39
    $("body").css("overflow", "hidden")
    
    $(document).bind('mousewheel', function(evt) {
        var delta = evt.originalEvent.wheelDelta
        console.log(delta)
    })
    

    works for me. adapted from How do I get the wheelDelta property?

    0 讨论(0)
  • 2020-12-01 14:45

    This is actually a somewhat indepth process. What I do is set global flags when users mouse enters and leaves the element that you want to scroll. Then, on the mousewheel event for the body I check to see if the MOUSE_OVER flag is true, then stop propagation of the event. This is so the main body doesnt scroll in case your entire page has overflow.

    Note that with overflow hidden, the default scrolling ability is lost so you must create it yourself. To do this you can set a mousewheel listener on your div in question and use the event.wheelDelta property to check whether the user is scrolling up or down. This value is different according to browser, but it is generally negative if scrolling down and positive if scrolling up. You can then change position of your div accordingly.

    This code is hacked up quickly but it would essentially look like this...

    var MOUSE_OVER = false;
    $('body').bind('mousewheel', function(e){
      if(MOUSE_OVER){
        if(e.preventDefault) { e.preventDefault(); } 
        e.returnValue = false; 
        return false; 
      }
    });
    
    $('#myDiv').mouseenter(function(){ MOUSE_OVER=true; });
    $('#myDiv').mouseleave(function(){ MOUSE_OVER=false; });
    
    $('#myDiv').bind('mousewheel', function(e){
      var delta = e.wheelDelta;
      if(delta > 0){
        //go up
      }
      else{
        //go down
      }
    });
    
    0 讨论(0)
  • 2020-12-01 14:46

    I use overflow:scroll, but also Absolutely position a div over the scroll bar in order to hide it.

    0 讨论(0)
提交回复
热议问题