开发者

Return true if key is down in javascript loop?

开发者 https://www.devze.com 2023-03-07 17:52 出处:网络
I want to add a condition inside a loop that tests if the right arrow is pressed and if it is move a div a bit to the right. However I don\'t know how to check for they keydown.

I want to add a condition inside a loop that tests if the right arrow is pressed and if it is move a div a bit to the right. However I don't know how to check for they keydown.

I'm using a code to do it but it is really long and I'm sure there is an shorter way to do it.

This 开发者_StackOverflowis the code:

    <div id="char"></div>
    <script>
    setInterval(function() {

// here it should check if RIGHT (keycode 39) is down and move char 10px to the right if it is;

    }, 20);
    </script>

How can I check for keydown inside the loop? Btw I'm also using jQuery on the site.

Thanks


Here ya go in raw JS you'd do something like this (press Preview then hold down w):

http://jsbin.com/odalo3/edit

var isPressed = false;

var keydown = function(e){ 
  if(e.keyCode == 87){
    isPressed = true;
  }
}
var keyup = function(e){
    isPressed = false;
}

document.addEventListener("keydown",keydown,false);
document.addEventListener("keyup",keyup,false);

setInterval(function(){
  if(isPressed){
    document.getElementById('hello').innerHTML = document.getElementById('hello').innerHTML+', pressed';
  } 
},100)

UPDATE

If you are using jQuery you can change the eventListeners to:

$(window).keydown(function(e){
   if(e.keyCode == 87){
     isPressed = true;
   }
})
.keyup(function(e){
  isPressed = false;
})

And delete these lines:

var keydown = function(e){ 
  if(e.keyCode == 87){
    isPressed = true;
  }
}
var keyup = function(e){
    isPressed = false;
}

document.addEventListener("keydown",keydown,false);
document.addEventListener("keyup",keyup,false);

But it's the same thing.


Use jQuery and keydown:

<div id="char"></div>
<script>
$(document).keydown(function(e){
    if(e.keyCode == 39){
          //do something
        $("#char").animate({'left':'+=10'}, 1);
     }
})
</script>

Fiddle: http://jsfiddle.net/maniator/zXeXt/


Create a flag var pressed; and set it to true or false in keyPress event; then check it inside the loop

0

精彩评论

暂无评论...
验证码 换一张
取 消