问题
I need an event that gives one click right, up, down or left. I want that when a condition is met (if) he give a click on the button I choose, below is an example in which should fit:
if (gesture.left) {
The click event in the left direction button keypad
} Else if (gesture.right) {
Click the event in the right direction button keypad
}
Do not want to detect which key was pressed, only one condition that after he click button that I want.
回答1:
arrow keys are only triggered by onkeydown
, not onkeypress
keycodes are:
- left = 37
- up = 38
- right = 39
- down = 40
http://jsfiddle.net/ahmadhasankhan/qqqpf/2/
回答2:
Try this code:
$(function(){
$('html').keydown(function(e){
if(e.keyCode == 37) { // left
}
else if(e.keyCode == 39) { // right
}
else if(e.keyCode == 38) { // up
}
else if(e.keyCode == 40) { // down
}
});
});
Demo
You can also use which
instead of keyCode
, Like following:
$(function(){
$('html').keydown(function(e){
if(e.which== 37) { // left
}
else if(e.which == 39) { // right
}
else if(e.which == 38) { // up
}
else if(e.which == 40) { // down
}
});
});
回答3:
<form>
<input id="target" type="text" value="Hello there">
</form>
<script>
$("#target").keydown(function(e){
if (e.keyCode == 37) {
alert( "left pressed" );
return false;
}else if (e.keyCode == 39) {
alert( "right key pressed" );
return false;
}else if (e.keyCode == 38) {
alert( "Up key pressed" );
return false;
}else if (e.keyCode == 40) {
alert( "Down key pressed" );
return false;
}
});
</script>
来源:https://stackoverflow.com/questions/23751582/click-event-on-the-keyboard-up-down-left-right