开发者

Ignoring delay when a key is held down?

开发者 https://www.devze.com 2023-04-05 11:12 出处:网络
Checked out other posts, no help... I\'m using asdw to move an object around within a limited space.I\'m trying to figure out how to allow the object to move around while the key is pressed, without

Checked out other posts, no help...

I'm using asdw to move an object around within a limited space. I'm trying to figure out how to allow the object to move around while the key is pressed, without the momentary delay at the beginning.

Thanks...

$(document).ready(function(){
    var longitude = 0;
    var latitude = 0;

    $('body#sense').keypress(function(){
        if(event.which == 65 || event.which == 97){
            // Left
            if(longitude != 0){
                longitude = longitude + 10;
                $('img#map').css('margin-left', longitude);
            }
        }
        else (event.which == 68 || event.which == 100){
            // Right
            if(longitude > -200){
                longitude = longitude - 10;
                $('img#map').css('margin-left', longitude);
            }
        }
    });
});

The web page

    <body id="sense">

<h2><center>Use your 'asdw' keys to move the map around</center></h2>

<div id="box">

<img id="map" sr开发者_开发技巧c="http://www.toronto.ca/culture/victoria-square/images/ch0/Victoria-Square-map-t.gif" alt="" />


</div>

</body>

The holding the image has a set width and height, both smaller than the image. The is set to overflow:hidden, so the javascript moves the image around within the div so different parts are visible.

The CSS

div#box {
    margin:0px auto;
    width:225px;
    height:225px;
    overflow:hidden;
}

div#box img {

}


Use the keyDown event and then start your own timer interval to control your own repeat interval (ignore the system repeat interval) and then cancel the timer on keyUp. Ignore the other key events. You can pick your own repeat time in the setInterval calls.

var timer = null;

function increaseLongitude() {
    // your code here
}

function decreaseLongitude() {
    // your code here
}

$("#sense").keyDown(function(e) {
    if (!timer) {
        if (e.which == 65 || e.which == 97) {
            timer = setInterval(increaseLongitude, 100);
            increaseLongitude();
        } else if (e.which == 68 || e.which == 100) {
            timer = setInterval(decreaseLongitude, 100);
            decreaseLongitude();
        }
    }
});

$("#sense").keyUp(function(e) {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
});


Try using the keydown event instead


Checkout this version of your code. it can be done with 'keydown' event. I believe this is the ideal way it should be done.

http://jsfiddle.net/valllabh/yFxDN/10/

0

精彩评论

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