<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>拖拽</title> <style> #ball { width: 50px; height: 50px; background-color: lightpink; border-radius: 50%; box-shadow: 2px 2px 1px #888; position:absolute; } </style> </head> <body> <div id="ball"></div> <script> // onmousedown: 选择, onmouseover: 移动, onmouseup:放下 var ball = document.getElementById('ball'); // 选中这个小球 // onmousedown //找到小球的位置: // 当前鼠标到小球边沿的距离相对是不变的,变得只是小球到左边与顶部的距离 // 这个不变的距离 ,是鼠标点击下去的一瞬间就确定了,就可以求出来了 // 根据当前鼠标到当前可视区的距离 // 求出鼠标当前位置 ball.onmousedown = function (event) { var x = event.clientX - this.offsetLeft; var y = event.clientY - this.offsetTop; console.log(x, y); // offsetLeft只读,返回数值 // 移太快,鼠标跑出小球了,怎么办, 应该把事件添加到整个文档就可以了,再快, 也不会跑出浏览器窗口吧 // ball.onmousemove = function (event) { document.onmousemove = function (event) { ball.style.left = event.clientX - x + 'px'; console.log(ball.style.left); // 注意返回的是字符串 ball.style.top = event.clientY - y + 'px'; } // ball.onmouseup = function () { document.onmouseup = function () { // ball.onmousemove = null; document.onmousemove = null; } } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例