| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <!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: fixed;
- top:0;
- left:0;
- }
- </style>
- </head>
- <body>
- <div class="box"></div>
- <script>
- // 获取元素
- var box = document.querySelector(".box");
- // 获取整个文档
- var doc = document.documentElement;
- // 绑定事件
- box.onmousedown = function(e){
- // 元素距离顶部的距离
- var docTop = box.offsetTop;
- // 元素距离左侧的距离
- var docLeft = box.offsetLeft;
- // 鼠标点击的位置距离顶部的间距
- var mouseTop = e.clientY;
- // 鼠标点击的位置距离左侧的间距
- var mouseLeft = e.clientX;
- // 获取鼠标点击位置距离元素顶部的间距
- var resTop = mouseTop - docTop;
- // 获取鼠标点击位置距离元素左侧的间距
- var resLeft = mouseLeft - docLeft;
- // 给整个文档绑定移动事件
- doc.onmousemove = function(event){
- // 拖动时 正方形的位置会改变
- box.style.left = event.clientX - resLeft + "px";
- box.style.top = event.clientY - resTop + "px";
- }
- }
- // 给整个文档绑定鼠标松开事件
- doc.onmouseup = function(){
- // 鼠标松开时 正方形停止移动
- doc.onmousemove = null;
- }
- </script>
- </body>
- </html>
|