A way to scroll an underlying div when mouse is on top of a fixed div?

前端 未结 4 1042
情歌与酒
情歌与酒 2020-12-03 05:15

The question is so long that coming up with a title that summarises it proved tricky.

So anyway. I have a div that has overflow: auto and t

相关标签:
4条回答
  • 2020-12-03 05:58

    What you are looking for is pointer-events: none;

    This makes the pointer not interact with that div essentially, so just do

    #fixed {
      pointer-events: none;
    }
    

    DEMO

    And you will get your desired outcome with no JS required. This will stop all other interaction with the div though, if you need to interact with it for some reason I'm afraid you'll have to look into a JS solution.

    0 讨论(0)
  • 2020-12-03 05:59

    I came up with a more elegant solution, however as it was Ruirize's answer that got me to the right track I gave him the accept tag.

    $('#fixed').on('mousewheel DOMMouseScroll', function(event) {
        $('#content').scrollTop($('#content').scrollTop() - (event.originalEvent.wheelDelta || -event.originalEvent.detail*30));
    });
    

    It is also displayed at jsFiddle.

    0 讨论(0)
  • 2020-12-03 06:06

    While the accepted answer definitely will get you the result you need, there is a noticeable difference in the smoothness of scrolling naturally and the scrolling triggered by setting scrollTop. This utilizes the best parts of pointer-events: none; without actually removing the ability to interact with your fixed elements.

    function enableScroll(e) {
      var self = $(this);
      self.css('pointer-events', 'none');
      clearTimeout(this.timer);
      this.timer = setTimeout(function () {
          self.css('pointer-events', 'all');
      }, 100);
    }
    $('#fixed').on('mousewheel DOMMouseScroll', enableScroll);
    
    0 讨论(0)
  • 2020-12-03 06:19
    var fixedElement = document.getElementById("fixed");
    
    function fixedScrolled(e) {
        var evt = window.event || e;
        var delta = evt.detail ? evt.detail * (-120) : evt.wheelDelta; //delta returns +120 when wheel is scrolled up, -120 when scrolled down
        $("#content").scrollTop($("#content").scrollTop() - delta);
    }
    
    var mousewheelevt = (/Gecko\//i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
    if (fixedElement.attachEvent)
        fixedElement.attachEvent("on" + mousewheelevt, fixedScrolled);
    else if (fixedElement.addEventListener)
        fixedElement.addEventListener(mousewheelevt, fixedScrolled, false);
    

    jsFiddle Demo - Scroll!

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