问题
QUESTION: how to get at the star above the numbers
My FIDDLE currently does not detect the * above the number row on the keyboard - only the * on the numeric keypad...
On my keyboard it is shift-3 so keyCode 51 + shift. How do I just test for * regardless of what I clicked to get it?
回答1:
The keydown
and keyup
events are unreliable for detecting specific characters, because the event.which property of these events are not char codes.
The keypress
event has to be used. This event may fire multiple times whilst a key is pressed down. So, set a flag when the desired key is pressed, and remove the flag on keyup
.
Demo: http://jsfiddle.net/xHnTD/
function something_to_do() {
// This function is fired when * is pressed.
$('<div>Pressed *!</div>').appendTo('body')
}
$('body').keypress(function(e) {
var $this = $(this);
if (e.which === 42) { // '*'.charCodeAt(0) === 42
if (!$this.data('rw_star_pressed')) {
$this.data('rw_star_pressed', true);
something_to_do();
}
}
}).keyup(function() {
$(this).removeData('rw_star_pressed');
});
回答2:
I'm not so sure about the keycodes you posted.
With this code, when I press *
I get 56
<script type="text/javascript">
document.addEventListener('keydown', function( event ) {
console.log(event.keyCode); });
</script>
来源:https://stackoverflow.com/questions/9841232/how-to-get-keypress-of-the-star-above-the-numbers