<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ padding: 0; margin: 0; list-style: none; } .leftBox, .rightBox{ width: 100px; height: 100px; border: 1px solid #000; position: relative; border-radius: 10px; display: inline-block; margin:100px; } .circle{ width: 50px; height: 50px; border-radius: 50%; background-color: yellowgreen; position: absolute; /*在盒子中居中*/ top: 50%; left: 50%; transform: translate(-50%,-50%); cursor: move; z-index: 2; } </style> </head> <body> <div class='leftBox'> <div class="circle"> </div> </div> <div class="rightBox"> </div> <script> var circle =document.querySelector(".circle"); circle.onmousedown = function (e) { e = e || window.event; var spaceX = e.clientX - circle.offsetLeft; var spaceY = e.clientY - circle.offsetTop; document.onmousemove = function (event) { event = event || window.event; circle.style.left = event.pageX - spaceX +'px'; circle.style.top = event.pageY - spaceY +'px'; } }; document.onmouseup = function () { document.onmousemove = null; }; </script> </body> </html>
简单拖拽案例
最新推荐文章于 2021-11-11 12:18:15 发布