How to disable scrolling temporarily?

前端 未结 30 2610
萌比男神i
萌比男神i 2020-11-21 05:16

I\'m using the scrollTo jQuery plugin and would like to know if it is somehow possible to temporarily disable scrolling on the window element through Javascript? The reason

30条回答
  •  Happy的楠姐
    2020-11-21 05:24

    galambalazs's solution is great! It worked perfectly for me in both Chrome and Firefox. And it also may be extended to prevent any default event from the browser window. Let's say you are doing an app on the canvas. You could do this:

    var events = {
      preventDefault: function(e) {
        e = e || window.event;
        if (e.preventDefault) e.preventDefault();
        e.returnValue = false;  
      },
    
      //spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36,
      //left: 37, up: 38, right: 39, down: 40
      keys: [32, 33, 34, 35, 36, 37, 38, 39, 40],
      keydown: function(e) {
        for (var i = events.keys.length; i--;) {
          if (e.keyCode === events.keys[i]) {
            events.preventDefault(e);
            return;
          }
        }
      },
    
      wheel: function(e) {
        events.preventDefault(e);
      },
    
      disable: function() {
        if (window.addEventListener) {
          window.addEventListener('DOMMouseScroll', events.wheel, false);
        }
        window.onmousewheel = document.onmousewheel = events.wheel;
        document.onkeydown = helpers.events.keydown;
      },
    
      enable: function() {
        if (window.removeEventListener) {
          window.removeEventListener('DOMMouseScroll', events.wheel, false);
        }
        window.onmousewheel = document.onmousewheel = document.onkeydown = null;  
      }
    }
    

    And then on your app let's say you're going to process your own events, like mouse, keyboard, touch events and so on... You could disable default events when the mouse goes inside the canvas and re-enable them when the mouse goes out:

    function setMouseEvents(canvas) {
      var useCapture = false;
    
      //Mouse enter event
      canvas.addEventListener('mouseenter', function(event) {
        events.disable();
      }, useCapture);
    
      //Mouse leave event
      canvas.addEventListener('mouseleave', function(event) {
        events.enable();
      }, useCapture);
    }
    

    You could even disable right click menu with this hack:

    function disableRightClickMenu(canvas) {
      var my_gradient = canvas.context.createLinearGradient(0, 0, 0, 225);
      my_gradient.addColorStop(0, "white");
      my_gradient.addColorStop(1, "white");
      canvas.context.fillStyle = my_gradient;
      canvas.context.fillRect(0, 0, canvas.width, canvas.height);
      canvas.oncontextmenu = function() { return false; };
    }
    

提交回复
热议问题