简体   繁体   中英

Check if the spacebar is being pressed and the mouse is moving at the same time with jQuery?

Is there a way to check if the space bar and at the same time track what direction the mouse is moving and how far etc.

Point of this is that I want to replicate how Photoshop scrolls when you hold the space bar, left mouse button and you move the mouse, but without having to hold down the left mouse button.

You can use keydown() and keyup() to track if the space bar is pressed or not and look at that state in your mousemove() event handler. For example:

var space = false;
$(function() {
  $(document).keyup(function(evt) {
    if (evt.keyCode == 32) {
      space = false;
    }
  }).keydown(function(evt) {
    if (evt.keyCode == 32) {
      space = true;
      console.log('space')
    }
  });
});

And then your mousemove() handler can see if it's pressed or not.

you will probably have to be watching for the keydown event, check to see that it's the spacebar, set a variable saying it's down, unset it when the keyup event is seen.

so, then you would look for mouse movements when that variable was set indicating the spacebar was pressed.

This is my solution:

var allowed = true;
$(document).ready(
function () {
    $(document).bind('keydown', 'space', function () {
        if (!allowed) return;
        allowed = false;
        $('#viewport').
            dragscrollable();
    });
    $(document).bind('keyup', 'space', function () {
        allowed = true;
        $('#base').off('mousedown');
        return false;
    });

});

Works with jQuery and the Dragscrollable Plugin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM