简体   繁体   English

当我在 javascript 中按下前进键或后退键时,我需要一种执行特定功能的方法

[英]I Need a way to execute a particular function when i press the forward key or the back key in javascript

I need a way to execute a particular function when I press the forward key or the back key in javascript.当我在 JavaScript 中按下前进键或后退键时,我需要一种执行特定功能的方法。 So that it may work when the forward button is pressed it may execute the function but it should work without taking the input in any type of text box.因此,当按下前进按钮时它可以工作,它可以执行该功能,但它应该在不接受任何类型文本框中输入的情况下工作。

I mean it should work on the whole page no matter where I am on the page but if I press the forward button the function should be executed.我的意思是无论我在页面上的哪个位置,它都应该在整个页面上工作,但是如果我按下前进按钮,则应该执行该功能。

I know how to do it by taking an input in a text box by matching the key codes but don't know how to make it work in someway else.我知道如何通过匹配键代码在文本框中输入来做到这一点,但不知道如何使其以其他方式工作。

If by forward and back keys you mean the arrow keys, this is how you can do it!如果前进和后退键是指箭头键,这就是您可以做到的!

document.onkeydown = function(e) {
e = e || window.event;
switch(e.which || e.keyCode) {
    case 37: // left
    break;

    case 38: // up
    break;

    case 39: // right
    break;

    case 40: // down
    break;

    default: return; // exit this handler for other keys
}
   e.preventDefault(); // prevent the default action
});

I feel pretty confident with my assumption that you are referring to the arrow keys on the keyboard.我对我的假设非常有信心,即您指的是键盘上的箭头键。 And as you say you already have working code for when a textbox is focused, I also assume you are using onkeydown (or one of the similar ones) already.正如您所说,您已经有了用于聚焦文本框的工作代码,我还假设您已经在使用onkeydown (或类似的其中之一)。 So the solution is to add the event listener to the document instead.所以解决方案是将事件侦听器添加到document

Like this for example:像这样例如:

document.onkeydown = function(e){
    // Your existing code goes here.
}

You need to use onkeydown if you want to detect arrow keys.如果要检测箭头键,则需要使用onkeydown

Here is a working example这是一个工作示例

Use onkeydown as this should work for all browsers.使用onkeydown因为这适用于所有浏览器。 I don't think onkeypress will work with google chrome for the arrow key events.我认为onkeypress不会与 google chrome 一起用于箭头键事件。

  • 38 = Up Arrow 38 = 向上箭头
  • 40 = Down Arrow 40 = 向下箭头

To find more you can use console.log(event.keyCode);要查找更多信息,您可以使用console.log(event.keyCode); in your onkeydown function to log the key codes to your browsers console.在您的onkeydown函数中,将键码记录到您的浏览器控制台。

 function MyFunc() { alert("Key up or down!"); } document.onkeydown = function() { if (event.keyCode == 38 || event.keyCode == 40) { MyFunc(); } }

If you have any questions please leave a comment below and I will get back to you as soon as possible.如果您有任何问题,请在下方留言,我会尽快回复您。

I hope this helps.我希望这有帮助。 Happy coding!快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM