练习

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin: 0;padding: 0;}
#wrap{500px;height:500px;border: 1px solid green;margin:10px auto; position:relative;}
#wrap img{position:absolute;top:0;left:0;}

</style>
</head>
<body>

    <div id="wrap">按Q统计步数~
        <img id="ren" src="images/b1.gif" alt="">
    </div>
    <script>


        // 获取小人的对象
        var Ren = document.getElementById('ren');

        // 绑定键盘按下的事件
        document.onkeydown = function(event){

            //    处理兼容性的问题
            var e = window.event || event;

            // 设置人 每次移动的步长
            var step = 10;

            /*
                w-87   s-83   a-65   d-68
            */
            switch (e.keyCode) {
                case 87: //
                    Ren.style.top = Math.max(0,Ren.offsetTop-step)+'px';
                    // Ren.style.top = Ren.offsetTop-step+'px';
                    changeImg('u1.gif','u2.gif');
                    break;
                case 83: //
                    // alert(Ren.offsetTop);  当前top 值
                    // Ren.style.top = Ren.offsetTop+step+'px';
                    // 向下的边界 top 470  如果470 大  就取470
                    Ren.style.top = Math.min(470,Ren.offsetTop+step)+'px';
                    changeImg('b1.gif','b2.gif');
                    break;
                case 65: //
                    // Ren.style.left = Ren.offsetLeft-step+'px';
                    Ren.style.left = Math.max(0,Ren.offsetLeft-step)+'px';
                    changeImg('l1.gif','l2.gif');
                    break;
                case 68: //
                    // Ren.style.left = Ren.offsetLeft+step+'px';
                    Ren.style.left = Math.min(470,Ren.offsetLeft+step)+'px';
                    changeImg('r1.gif','r2.gif');
                    break;
                case 81:
                    alert('您一共走了'+i+'步~');
            }
        }


        // // 换图方法
        // function changeImg(img1,img2){
        //     // 从绝对路径中截取 文件名
        //     var newTu = Ren.src.substr(Ren.src.lastIndexOf('/')+1);
        //     // 根据方向来确定显示的图片
        //     if(newTu == img1){
        //         Ren.src = 'images/'+img2;
        //     }else{
        //         Ren.src = 'images/'+img1;
        //     }
        // }
        var i = 0;
        function changeImg(img1, img2){
            if(i%2==0){ //或许只写i%2也是对的
                Ren.src = 'images/'+img2;
            }else{
                Ren.src = 'images/'+img1;
            }
            i++;
        }
    </script>

 在线地址:http://yupinghua.com/practices/components/%E5%B0%8F%E4%BA%BA%E7%A7%BB%E5%8A%A8.html

原文地址:https://www.cnblogs.com/yupinghua/p/6380122.html