Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

javascript - jQuery Move div with arrow keys

I'm trying to move a div using the arrow keys. I have the following code which is not working for me. Do you see anything wrong with it. Check jsfiddle at http://jsfiddle.net/N5Ltt/1/

$(document).keydown(function(e) {
    switch (e.which) {
    case 37:
        $('div').stop().animate({
            left: '-= 10'
        }); //left arrow key
        break;
    case 38:
        $('div').stop().animate({
            top: '-= 10'
        }); //up arrow key
        break;
    case 39:
        $('div').stop().animate({
            left: '+= 10'
        }); //right arrow key
        break;
    case 40:
        $('div').stop().animate({
            top: '+= 10'
        }); //bottom arrow key
        break;
    }
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two things you need to do:

  1. Your <div> needs position: absolute or your top and left properties won't do anything.
  2. jQuery doesn't know what '-= 10' means but it does understand '-=10'. You might want to go all the way to '-=10px' as that's more common but the px isn't necessary.

Updated fiddle: http://jsfiddle.net/ambiguous/N5Ltt/2/

You're seeing the animation stop when you hold down an arrow key because you call .stop on each keydown and that stops the animation. The animation works using a timer and .stop stops the timer; if the keyboard's repeat rate is faster than the first iteration of the timer then no animation happens when you hold down an arrow key. You're only moving by 10px at a time so you could just do a straight non-animated move by 10px using .css:

$div.css('left', $div.offset().left - 10);

Non-animated version: http://jsfiddle.net/ambiguous/N5Ltt/3/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...