#动画 拖拽
<!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>Document</title> <style> *{ margin:0; padding:0; } .box{ width:500px; height:500px; margin:0 auto; border:10px dashed blue; position:relative; } .box1{ width:100px; height:100px; background-color:aquamarine; border-radius:50%; top:0; left:0; position:absolute; } </style> </head> <body> <div class="box"> <div class="box1"></div> </div> <script> // 获取元素 var box = document.querySelector(".box"); var box1 = document.querySelector(".box1"); box1.onmousedown = function(e) { // 记录鼠标按下时的位置 var nowX = e.clientX; var nowY = e.clientY; // 记录鼠标按下时box1的位置 var left = box1.offsetLeft; var top = box1.offsetTop; document.onmousemove = function(e){ // 鼠标移动后的位置 var mouseX = e.clientX; var mouseY = e.clientY; // var X = mouseX - nowX; // var Y = mouseY - nowY; // box1.style.left = left + X + "px"; // box1.style.top = top + Y + "px"; // 计算鼠标移动了多少 var resultX = mouseX - nowX + left; var resultY = mouseY - nowY + top; if(resultX < 0){ resultX = 0 }else if(resultX > box.clientWidth - box1.clientWidth){ resultX = box.clientWidth - box1.clientWidth } if(resultY < 0){ resultY = 0 }else if(resultY > box.clientHeight - box1.clientHeight){ resultY = box.clientHeight - box1.clientHeight } box1.style.left = resultX + "px"; box1.style.top = resultY + "px"; } } document.onmouseup = function(){ document.onmousemove = null; } </script> </body> </html>