男人与keydown跳跃的幻觉

Leg*_*ary 9 css jquery keydown

所以我想创建一个小页面,你可以让一个人跳过一个盒子,它全部用CSS和jQuery.

如果你按下右箭头键,整个背景向左移动,而另一个方向向左箭头键移动,我就这样做了,以使人产生幻觉.知道什么时候你打空间我改变了男人的最低位置让我看起来像是在跳跃.

但是当我击中太空时,它会停止移动效果,所以男人只是直接向下跳.

我的HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>The man!</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script type="text/javascript" src="jquery1.10.2.js"></script>
<script type="text/javascript" src="main_script.js"></script>
</head>
<body>
    <div id="canvas">
        <div id="grass"></div>
        <div id="box"></div>
        <div id="man"></div>
    </div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的CSS:

html, body {
    height: 100%;
}

body {
    margin: 0;
    padding: 0;
    overflow: hidden;
}

#canvas {
    position: relative;
    min-width: 2500px;
    height: 100%;
}

#grass {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 100px;
    background: green;
}

#box {
    position: absolute;
    bottom: 100px;
    left: 2000px;
    width: 100px;
    height: 100px;
    background: brown;
}

#man {
    position: fixed;
    bottom: 100px;
    left: 500px;
    width: 73px;
    height: 161px;
    background-image: url(images/mand.png);
    background-repeat: no-repeat;
    background-position: 0 0;
        -webkit-transition: bottom 0.5s ease-in-out;
        -moz-transition: bottom 0.5s ease-in-out;
        -ms-transition: bottom 0.5s ease-in-out;
        -o-transition: bottom 0.5s ease-in-out;
        transition: bottom 0.5s ease-in-out;
}
Run Code Online (Sandbox Code Playgroud)

我的剧本:

    $( document ).ready(function() {

    });

    $(document).keydown(function(event) {
    console.log("Key pressed: " + event.keyCode);

    if(event.keyCode == 39) {
        event.preventDefault();
        $("#canvas").animate({
        marginLeft: "-=10px"
      }, 1)
    }

    if(event.keyCode == 37) {
        event.preventDefault();
        if($("#canvas").css('margin-left') < '0px') {
            $("#canvas").animate({
            marginLeft: "+=10px"
            }, 1)
        }
    }

    if(event.keyCode == 32) {
        event.preventDefault();
        setTimeout(function() {
        $("#man").css("bottom", "300px");
        setTimeout(function() {
        $("#man").css("bottom", "100px");
        },500);},0); 
    }
});
Run Code Online (Sandbox Code Playgroud)

我也做了一点小事:JSFiddle

Ton*_*ony 2

似乎无法同时发送 2 个向下键的呼叫事件处理程序。实际上这是正常的(请参阅此处的更多详细信息:JavaScript 多个键同时按下)。您需要处理 keyDown 和 keyUp 事件来切换“运行”状态,如下所示(伪代码!请参阅下面的小提琴中的 woking 示例):

$(document).keydown(function(event) {
    // switch your man to a "running" state
    startRunning();
})
.keyup(function(event) {
    // switch to a "hold" state
    stopRunning();
});
Run Code Online (Sandbox Code Playgroud)

完整演示