最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript when holding down arrow keys? - Stack Overflow

programmeradmin1浏览0评论

I have this script to trigger some javascript. But the script does not support holding down the arrow keys. How can I make this work when I hold the arrow keys.

document.onkeyup = KeyCheck;       
function KeyCheck()
{
    var KeyID = event.keyCode;

    switch(KeyID)
    {
      case 37:
      right('img'); document.getElementById('img').src = 'guyl.png';
      break;
      
      case 38:
      up('img');
      break

      case 39:
      left('img'); document.getElementById('img').src = 'guyr.png';
      break;

      case 40:
      down('img');
      break;   
     }
}

I have this script to trigger some javascript. But the script does not support holding down the arrow keys. How can I make this work when I hold the arrow keys.

document.onkeyup = KeyCheck;       
function KeyCheck()
{
    var KeyID = event.keyCode;

    switch(KeyID)
    {
      case 37:
      right('img'); document.getElementById('img').src = 'guyl.png';
      break;
      
      case 38:
      up('img');
      break

      case 39:
      left('img'); document.getElementById('img').src = 'guyr.png';
      break;

      case 40:
      down('img');
      break;   
     }
}
Share Improve this question edited Jul 24, 2021 at 1:10 General Grievance 4,98838 gold badges37 silver badges55 bronze badges asked Mar 10, 2011 at 2:32 Trevor RudolphTrevor Rudolph 1,0634 gold badges18 silver badges42 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 11

should be:

document.onkeydown = KeyCheck;

onkeypress : invokes JavaScript code when a key is pressed

onkeydown : invokes JavaScript code when a key is held down (but not yet released)

onkeyup : invokes JavaScript code when a key is has been released after being pressed.

You just need to handle the onkeydown event.

  1. correct your function to accept the event arg

    function KeyCheck(event) {
      var KeyID = event.keyCode;
      ...
    }
    
  2. if you want to use combination of keys, then use onkeypress event instead, push the keys into array and see if you have desired combination to follow.

发布评论

评论列表(0)

  1. 暂无评论