jquery animate只用keypress事件触发一次

时间:2014-11-12 01:12:11

标签: javascript jquery event-handling

尝试使用awsd键移动p元素以移动2D galactica样式。 这些密钥只工作一次,无需刷新页面。

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Moving with arrows</title>
    <link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
    <p>Hello World!</p>
    <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script src="app.js"></script>
</body>
</html>

jQuery(console.log显然只是为了学习密钥代码)

var main = function () {

$("body").on("keypress", function (event) {
    console.log(event.keyCode);

    if (event.keyCode === 97) {
        $("p").animate({right: "5px"});
    }
    else if (event.keyCode === 100) {
        $("p").animate({left: "5px"});
    }
    else if (event.keyCode === 119) {
        $("p").animate({bottom: "5px"});
    }
    else if (event.keyCode === 115) {
        $("p").animate({top: "5px"});
    }
});
};

$(document).ready(main);

风格

body {
background: black;
width: 750px;
height: 100%;
margin: auto;
}

p {
position: relative;
width: 100px;
text-align: center;
padding-top: 10px;
padding-bottom: 10px;
margin: auto;
margin-top: 50%;
color: white;
background: grey;
border-radius: 10px;
}

1 个答案:

答案 0 :(得分:1)

一旦您将实例top设置为5px,下次按下按钮时您会发生什么?您必须增加,在jQuery中,您可以使用+=-=来执行此操作

$("body").on("keypress", function (event) {
    if (event.keyCode === 97) {
        $("p").animate({
            left: "-=5px"
        });
    } else if (event.keyCode === 100) {
        $("p").animate({
            left: "+=5px"
        });
    } else if (event.keyCode === 119) {
        $("p").animate({
            top: "-=5px"
        });
    } else if (event.keyCode === 115) {
        $("p").animate({
            top: "+=5px"
        });
    }
});

FIDDLE