如何同时检测按键和鼠标hover

好的,所以我可以使用.on('mouseover')检测鼠标.on('mouseover')

我可以使用检测按键

 $(document).keypress(function(e) { console.log(e.which); } 

但是当我按下某个按钮时,如何检测鼠标hover在哪个图像上?

我的想法是能够在将鼠标hover在图像上时按d来删除图像。 有任何想法吗 ?

您可以切换一个类或数据属性,以显示当前正在hover的那个

 $('img').hover(function(){ $(this).toggleClass('active'); // if hovered then it has class active }); $(document).keypress(function(e) { if(e.which == 100){ $('.active').remove(); // if d is pressed then remove active image } }); 

小提琴

我用jsFiddle添加了一个更好的例子: http : //jsfiddle.net/cUCGX/ (将鼠标hover在其中一个框上并按回车键。)


为每个图像打开(“鼠标hover”)并根据该图像设置变量。

所以

 var activeImage = null; myImage.on('mouseover', function() { activeImage = 'myImage'; }); myImage2.on('mouseover', function() { activeImage = 'myImage2'; }); $(document).keypress(function(e) { if (e.which == 'certainKeyPress' && activeImage) { //do something with activeImage console.log('The cursor was over image: ' + activeImage + ' when the key was pressed'); } }); 

如果您希望按键仅在hover时工作,也可以为每个图像添加一个onmouseout以清除activeImage。

您应该使用mousemove事件将x和y位置永久存储在全局变量中。

然后,在按键处理程序中,使用document.elementFromPoint(x,y)方法在最后已知的鼠标位置抓取元素。

请参阅https://developer.mozilla.org/en-US/docs/Web/API/document.elementFromPoint

当我正在玩这个时,我会继续前进和坏死,发现我更喜欢我的快速解决方案。 它可能不是最好的,但它更适合我需要的命名空间类型解决方案,因为当dom处于某种状态时可以删除处理程序(可排序):

 // Create handler for binding keyup/down based on keyCode // (ctrl in this example) with namespace to change the cursor var setCursorBindings = function() { $(document).on('keydown.sortable', function(event) { if (event.keyCode === 17) { $('body').css('cursor', 'pointer'); } }).on('keyup.sortable', function(event) { if (event.keyCode === 17) { $('body').css('cursor', 'inherit'); } }); }; // Create a handler for reverting the cursor // and remove the keydown and keyup bindings. var clearCursorBindings = function() { $('body').css('cursor', 'inherit'); $(document).off('keydown.sortable').off('keyup.sortable'); }; // Use the jQuery hover in/out to set and clear the cursor handlers $('.myElementSelector').hover(function() { setCursorBindings(); }, function() { clearCursorBindings(); }); 

在Chrome v41中测试过

使用它来测试鼠标是否在id img的图像上:

 $('#img').is(":hover")