使用jquery" keydown"移动"框"周围

时间:2014-07-25 20:14:07

标签: jquery html css

我正在尝试制作类似游戏的东西而且我遇到了问题。我在谷歌上搜索了很多而无法找到答案。我正在尝试使用jquery" keydown"改变我的"元素的选项"翻页。
示例:如果按下right key,则需要检测"框"的前一个位置。移动它" + 10px"正确的。
我希望你有任何教程或建议,我可以从哪里开始:) 这是我来到的地方 的 HTML

<div id="movingBox"></div>

CSS

#movingBox{
    width:20px;
    height:20px;
    background:blue;
}

你可以找到我的jsfiddle here

4 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

<强> JS

$(document).keydown(function(e) {
    switch (e.which) {
    case 37:
        $('#movingBox').stop().animate({
            left: '-=10'
        }); //left arrow key
        break;
    case 38:
        $('#movingBox').stop().animate({
            top: '-=10'
        }); //up arrow key
        break;
    case 39:
        $('#movingBox').stop().animate({
            left: '+=10'
        }); //right arrow key
        break;
    case 40:
        $('#movingBox').stop().animate({
            top: '+=10'
        }); //bottom arrow key
        break;
    }
})

<强> CSS

#movingBox{
    width:20px;
    height:20px;
    background:blue;
    position:absolute;
    top: 0;
    left: 0;
}

fiddle

答案 1 :(得分:1)

您将需要以下内容来完成它。只需查看与键盘上的键对应的键码,并将其替换为13.这应该让您从正确的方向开始。

$( "#target" ).keydown(function( event ) {
  if ( event.which == 13 ) {
  event.preventDefault();
}

  var msg = "Handler for .keydown() called " + xTriggered + " time(s).";
  $.print( msg, "html" );
  $.print( event );
});

答案 2 :(得分:1)

如果我可以评论,我会这样做,但我没有声誉。无论如何,请看一下这个JSFiddle

HTML:

<img id="plane" src='http://i.imgur.com/WmhK6mX.png' border='0'/>

使用Javascript:

setInterval(movePlane, 20);
var keys = {}

$(document).keydown(function(e) {
    keys[e.keyCode] = true;
});

$(document).keyup(function(e) {
    delete keys[e.keyCode];
});


function movePlane() {
    for (var direction in keys) {
        if (!keys.hasOwnProperty(direction)) continue;
        if (direction == 37) {
            $("#plane").animate({left: "-=5"}, 0);                
        }
        if (direction == 38) {
            $("#plane").animate({top: "-=5"}, 0);  
        }
        if (direction == 39) {
            $("#plane").animate({left: "+=5"}, 0);  
        }
        if (direction == 40) {
            $("#plane").animate({top: "+=5"}, 0);  
        }
    }
}

CSS:

body{
background:white;
}
#plane {
    height: 50px;
    position:absolute;
    top:40%;
    left:40%;
}

你可以从这里开始。看看正在做什么,并尝试改变一些元素,以了解它。然后,将此作为您尝试做的事情的基础。如果您还有其他问题,我可以尽力提供帮助。

答案 3 :(得分:1)

您可以使用jquery animate函数移动框。我在自己的游戏中使用了这种方法:

HTML:

<div id="movingBox"></div>

CSS:

#movingBox{
    width:20px;
    height:20px;
    background:blue;
    position:absolute;
}

JS:

$(function(){
    $("html").keydown(function(k){
        if(k.which == 39){
            $("#movingBox").animate({left: "+=50"},100);
        }

    });

});

http://jsfiddle.net/Jx2cn/4/