我试图找出使用jQuery用 ctrl 键按下的字符,但我无法找出代码。
例如:如果我按 ctrl + a 那么它应该提示我 ctrl + a 被按下
我正在使用以下代码
$(document).keypress(function(e) {
if(e.ctrlKey){
var ch = String.fromCharCode(e.keyCode);
alert("key pressed ctrl+"+ch); //gives blank value in ch here, I need to know the character pressed
alert("key pressed ctrl+"+e.keyCode); //this works but gives me ASCII value of the key
}
});
答案 0 :(得分:2)
您必须使用keydown
事件可靠地捕获密钥代码:
$(document).keydown(function(event) {
console.log(event);
if (!event.ctrlKey){ return true; }
$("#result").text(String.fromCharCode(event.which));
event.preventDefault();
});
答案 1 :(得分:0)
<html>
<head>
<title>ctrlKey example</title>
<script type="text/javascript">
function showChar(e){
alert(
"Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
+ "charCode: " + e.charCode + "\n"
+ "CTRL key pressed: " + e.ctrlKey + "\n"
);
}
</script>
</head>
<body onkeypress="showChar(event);">
<p>Press any character key, with or without holding down the CTRL key.<br />
You can also use the SHIFT key together with the CTRL key.</p>
</body>
</html>