Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

javascript - How to detect a keypress AND a mouseover at the same time

Okay so I can detect a mouseover using .on('mouseover')

and I can detect keypresses using

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

but how do I detect which image my mouse is hovering over when I press a certain button?

the idea is to be able to delete an image by pressing d while hovering over it. any ideas ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can just toggle a class or data-attribute that shows you which one is currently being hovered

$('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
    }
});

FIDDLE


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...