| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- <!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: 300px;
- height: 300px;
- background: yellowgreen;
- cursor: pointer;
- margin-left: 20px;
- position: absolute;
- /* left: 300px; */
- }
- </style>
- </head>
- <body>
- <div id="box"></div>
- <script>
- var box = document.getElementById("box");
- box.onmousedown = function(event) {
- console.log(event)
- // event.clientX event.clintY 事件触发时 鼠标所在的X,Y坐标
- // 计算鼠标在元素内部的偏移量
- var left1 = event.clientX - box.offsetLeft;
- var top1 = event.clientY - box.offsetTop;
- // 移动事件 绑定给document
- document.onmousemove = function(event) {
- box.style.left = event.clientX - left1 + 'px';
- box.style.top = event.clientY - top1 + 'px';
- }
- }
- // 抬起事件
- document.onmouseup = function() {
- document.onmousemove = null;
- }
- </script>
- </body>
- </html>
|