Javascript 用jQuery检查是否按下空格键和鼠标同时移动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2249203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if the spacebar is being pressed and the mouse is moving at the same time with jQuery?
提问by Colin
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.
这一点是我想复制当您按住空格键、鼠标左键并移动鼠标时 Photoshop 的滚动方式,但不必按住鼠标左键。
回答by cletus
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:
您可以使用keydown()和keyup()来跟踪空格键是否被按下,并在您的mousemove()事件处理程序中查看该状态。例如:
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.
然后您的mousemove()处理程序可以查看它是否被按下。
回答by John Boker
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.
您可能必须监视 keydown 事件,检查它是否是空格键,设置一个变量表示它已关闭,当看到 keyup 事件时取消设置它。
so, then you would look for mouse movements when that variable was set indicating the spacebar was pressed.
因此,当设置该变量指示按下空格键时,您将查找鼠标移动。
回答by vanLushi
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.
适用于 jQuery 和 Dragscrollable 插件。

