HTML 方块移动

 两个方块的样式,小的方块在大的方块里面。

    *{
            margin: 0;
            padding: 0;
        }
        #box{
            position: relative;
            margin: 30px auto 0;
            width: 760px;
            height: 760px;
            background: skyblue;
        }
        #box1{
            position: absolute;
            left: 360px;
            top: 360px;
            width: 40px;
            height: 40px;
            background: red;
        }

     <div id="box">
                <div id="box1"></div>
        </div>

 

小方块移动的js:

        var box=document.getElementById('box');
        var box1=document.getElementById('box1');
        document.onkeydown=function(event){
                var e = event || window.event || arguments.callee.caller.arguments[0];
                // odiv.style.left = "40px"是固定的值
                // odiv.style.left = odiv.offsetLeft是变量
                // 也就是说odiv.offsetLeft值每运行一次就会改变一次值,所以才会有DIV可以动多次的效果
                
                // 让小方块在大方块里面移动,但不能移动到大方块外面
                
                // 向左移动时,用来判断到左边距
                var w= box1.offsetLeft;
                
                 // 向top移动时,用来判断到top边距
                var h= box1.offsetTop;
                 
                 // 向right移动时,用来判断里左边距
                var w1=box.offsetWidth-box1.offsetLeft-40;

                // 向up移动时,用来判断到top边距
                var h1=box.offsetHeight-box1.offsetTop-40;
                
                // left
                if(e && e.keyCode==37){
                    if(w> 0){
                         box1.style.left = box1.offsetLeft-40+ "px"; 
                         console.log('left')
                    }
                }
                // up
                if(e && e.keyCode==38){
                    if(h>0){
                        box1.style.top = box1.offsetTop-40+ "px";
                        console.log('up')
                    }
                }
                // right
                if(e && e.keyCode==39){
                    if(w1>0){
                        box1.style.left = box1.offsetLeft+40+ "px";
                        console.log('right')
                    }
                }
                // down
                if(e && e.keyCode==40){
                    if(h1>0){
                        box1.style.top = box1.offsetTop+40+ "px";
                        console.log('down')
                    }
                }
        }

希望得到大家意见,改进代码!!!谢谢

posted @ 2020-09-20 21:55  序丶m  阅读(617)  评论(0)    收藏  举报