123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- <!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 class="box"></div>
- <script>
- var oBox = document.getElementsByClassName("box")[0];
- var oDom = document.documentElement;
- oBox.onmousedown = function (e) {
- // 获取鼠标点击的位置
- var x = e.clientX;
- var y = e.clientY;
- // 获取盒子距离页面顶部的距离
- var boxTop = oBox.offsetTop;
- // 获取盒子距离页面左边的距离
- var boxLeft = oBox.offsetLeft;
- // 获取鼠标点击位置 在盒子里的位置
- var thisTop = y - boxTop;
- var thisLeft = x - boxLeft;
- oDom.onmousemove = function (e) {
- oBox.style.top = e.clientY - thisTop + "px";
- oBox.style.left = e.clientX - thisLeft + "px";
- console.log("move")
- }
- }
- oBox.onmouseup = function () {
- oDom.onmousemove = null;
- }
- </script>
- </body>
- </html>
|