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

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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,695评论 1 45
  • 1 Webpack 1.1 概念简介 1.1.1 WebPack是什么 1、一个打包工具 2、一个模块加载工具 3...
    Kevin_Junbaozi阅读 6,726评论 0 16
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,796评论 1 92
  • 重要的事说三遍! 今天干了一件蠢事。 早早起床,送娃上学。回来路上买了早点,准备带回来吃。就放车筐里了。回来看小瓶...
    大白兔真的喜欢萝卜嘛阅读 348评论 2 3
  • 山竹来了,今年最强的台风。 趁着学校停课,我便咸鱼了一整天。想着在前几天上的英雄联盟白金一的基础上再进一步,完成我...
    圭暮阅读 100评论 0 0