开发者社区> 问答> 正文

javascript代码的小div为什么向上和向左移动不了

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="Generator" content="EditPlus®">
 <meta name="Author" content="">
 <meta name="Keywords" content="">
 <meta name="Description" content="">
 <title>Document</title>
</head>
<body>
    <tbody>
           <div style="background-color:black;height:500px;width:600px" >
               <div id="mytanke" style="background-color:yellow;width:18px;height:20px;position:relative;"></div>
           </div>
    </tbody>
    <script type="text/javascript">
       var mytanke=document.getElementById("mytanke");

       document.onkeydown=function(event){


           var e = event || window.event || arguments.callee.caller.arguments[0];
           var x=mytanke.offsetLeft;
           var y=mytanke.offsetTop;
           if(e && e.keyCode==37){ // zuo
               mytanke.style.backgroundColor='red';
               if(x>8){

                   mytanke.style.left=(x-1)+'px';
               }
           }
           if(e && e.keyCode==38){ // shang

               if(y>8){

                   var mm=parseInt(y)-1;


                   mytanke.style.top=mm+'px';
               }
           }            
           if(e && e.keyCode==39){ // you

                 if(x<600){

                     console.log(3333);
                   mytanke.style.left=(x+1)+'px';
               }
           }
           if(e && e.keyCode==40){ // xia
               console.log(4444);
               if(y<500){

                   mytanke.style.top=(y+1)+'px';
               }
           }
        }; 
    </script>
</body>
</html>

展开
收起
小旋风柴进 2016-06-01 16:58:44 2045 0
1 条回答
写回答
取消 提交回答
  • 亲,你这段代码写得有点问题哦~
    你给元素 style 的 left/top/right/bottom 赋值都是根据相关 offsetTop、offsetLeft 来的。offsetLeft 不等于元素 style 的 left,在你举的例子里面,页面 body 默认有 margin: 8px , 初始化的时候小方块的 offsetLeft 就是 8 了。当你按下向右的按钮的时候,赋值 style.left = offsetLeft + 1 + 'px' 实际上就是 style.left = 8 + 1 + 'px'style.left = '9px'。变更之后 left 为 9px,offsetLeft 为 8 + 9 = 17;此时当你按下向左的按钮的时候是赋值 style.left = offsetLeft - 1 + 'px'style.left = 17 - 1 + 'px'style.left = '16px',比之前的 9px 又多了 7px 呢,所以方块继续向右移动了!
    主要的原因还是 offsetLeft 不等于元素的 left,这里需要处理下。

    2019-07-17 19:23:32
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
JavaScript函数 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载