fengchuanyu 2 هفته پیش
والد
کامیت
6194189bce
1فایلهای تغییر یافته به همراه41 افزوده شده و 0 حذف شده
  1. 41 0
      4-BOM&DOM/练习8_移动正方形.html

+ 41 - 0
4-BOM&DOM/练习8_移动正方形.html

@@ -0,0 +1,41 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Document</title>
+    <style>
+        #box{
+            width: 100px;
+            height: 100px;
+            background-color: red;
+            position: absolute;
+        }
+    </style>
+</head>
+<body>
+    <div id="box"></div>
+    <script>
+        // 第一步获取元素 正方形
+        var oBox = document.getElementById("box");
+        // 获取页面
+        var oPage = document.documentElement;
+
+        // 第二步给元素添加事件 给正方形绑定鼠标按下事件
+        oBox.onmousedown = function(e){
+            // 记录鼠标点击时在正方形的哪个位置
+            var x = e.offsetX;
+            var y = e.offsetY;
+            // 第三步给页面绑定移动事件
+            oPage.onmousemove = function(e){
+                oBox.style.top = (e.clientY - y)+ "px";
+                oBox.style.left = (e.clientX - x)+ "px";
+            }
+        }
+        // 第四步移除页面移动事件
+        oBox.onmouseup = function(){
+            oPage.onmousemove = null;
+        }
+    </script>
+</body>
+</html>