美文网首页
Day28--课后作业(方块移动)

Day28--课后作业(方块移动)

作者: zxhlcl | 来源:发表于2018-11-08 21:05 被阅读0次

CSS代码:

<style type="text/css">
            #cube{
                position:absolute ;
                width: 100px;
                height: 100px;
                background-color: lightblue;
                left:30px;
                top:30px;
            }
        </style>

JS代码:

<script type="text/javascript">
            !function(){    
                var cube=document.getElementById("cube");
                var currentStyle=document.defaultView.getComputedStyle(cube);
                var xDown,yDown,left,top,xMove,yMove;
                
                function startMove(evt){
                    xDown=evt.clientX;
                    yDown=evt.clientY;
                    left=currentStyle.left;
                    top=currentStyle.top;
                    cube.addEventListener("mousemove",moving);
                }
                function moving(evt){
                    xMove=evt.clientX;
                    yMove=evt.clientY;
                    var xDistanse=xMove-xDown;
                    var yDistanse=yMove-yDown;
                    cube.style.top=(parseInt(top)+yDistanse)+"px";
                    cube.style.left=(parseInt(left)+xDistanse)+"px";
                }
                function stopMove(evt){
                    cube.removeEventListener("mousemove",moving);
                    cube.style.top=document.defaultView.getComputedStyle(cube).top;
                    cube.style.left=document.defaultView.getComputedStyle(cube).left;
                }
                
                cube.addEventListener("mousedown",startMove);
                cube.addEventListener("mouseup",stopMove);  
            }();
            
            
        </script>

相关文章

网友评论

      本文标题:Day28--课后作业(方块移动)

      本文链接:https://www.haomeiwen.com/subject/pwjgxqtx.html