How to get keypress of the star above the numbers

家住魔仙堡 提交于 2019-12-25 07:58:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!