2015-08-17 26 views
-1

我有一些功能。例如使用.keypress運行函數jQuery

<script> 

//Function1 
alert('Function 1 run') 

//Function2 
alert('Function 2 run') 

</script> 

我需要.keypress jQuery運行該功能,例如按special key 1 + special key 2Ctrl + Character

<script> 

('html').on('keypress' , ' Ctrl + A ' , function() { 

    alert('Function 1 run') 

}); 

('html').on('keypress' , ' Ctrl + B ' , function() { 

    alert('Function 2 run') 

}); 

</script> 

所以你會u人建議我?

+0

沒有嘗試'$(文件)。在('按鍵...' – joyBlanks

+0

** [鏈接](HTTP:/ /stackoverflow.com/questions/2767126/how-to-detect-that-c​​trlr-was-pressed)**,** [鏈接](http://stackoverflow.com/questions/2903991/how-to-detect- ctrlv-ctrlc -using-javascript)**和** [鏈接](http://stackoverflow.com/questions/9374915/javascript-detect-ctrl-key-pressed-or-up-keypress-event-doest-trigger )**。 –

+0

您可以使用jquery插件作爲hotkeys.js –

回答

1

事件​​將捕獲Ctrl按鈕,它被保持的值將爲true。儘管如此,我認爲最好使用一些插件,因爲可能會出現許多瀏覽器兼容性問題。

$(document).on('keydown',function(event){ 
 
    if(event.ctrlKey && (event.which == 65)){ 
 
     alert('Ctrl+A'); 
 
    event.preventDefault(); 
 
    } 
 
    if(event.ctrlKey && (event.which == 66)){ 
 
     alert('Ctrl+B'); 
 
    event.preventDefault(); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

1

剛剛嘗試這一點,

$(document).keypress(function(e) { 
    if(e.ctrlKey && e.key == "a") { 
     alert('function 1'); 
    } 
    if(e.ctrlKey && e.key == "b") { 
     alert('function 2'); 
    } 
});