[英]Extend javascript key pressed function
I've a such a small javascript on my website, to control the site by pressing the arrow keys on my keyboard. 我在我的网站上有一个这么小的javascript,通过按键盘上的箭头键来控制网站。
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
leftArrowPressed();
break;
case 39:
rightArrowPressed();
break;
}
};
function rightArrowPressed() {
window.open("next-page.php","_self")
}
function leftArrowPressed() {
window.open("pre-page.php","_self")
}
If I'm pressing the right-arrow-key the javascript redirects me to the "next-page.php". 如果我按下右箭头键,javascript会将我重定向到“next-page.php”。 If I'm pressing the left-arrow-key the javascript redirects me to the "pre-page.php". 如果我按下左箭头键,javascript会将我重定向到“pre-page.php”。
I want to extend the script with pressing the + and - key or the q and w key. 我想通过按+和 - 键或q和w键来扩展脚本。 The current script should not change ideally. 当前脚本不应该理想地改变。
The keyCode for what you want to do are the following : 您要执行的操作的keyCode如下:
+ : 107
- : 109
q : 81
w : 88
So using your code, here is what we could do : 所以使用你的代码,这是我们可以做的:
document.onkeydown = function(evt) {
evt = evt || window.event;
switch (evt.keyCode) {
case 37:
//code here
break;
case 88:
//code here
break;
case 109:
leftArrowPressed();
break;
case 39:
//code here
break;
case 81:
//code here
break;
case 107:
rightArrowPressed();
break;
}
};
Inside of document.onkeydown
after you've defined evt
, log the keyCode
values: 在定义evt
之后的document.onkeydown
,记录keyCode
值:
console.log(evt.keyCode);
From there you can modify your switch
statement as necessary. 从那里你可以根据需要修改你的switch
语句。
You can check this: 你可以检查一下:
switch (evt.keyCode) {
case 37:
leftArrowPressed();
break;
case 39:
rightArrowPressed();
break;
case 107: // for +
your script
break;
case 109: // for -
your script
break;
case 81: // for q
your script
break;
case 87: // for w
your script
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.