动画 实现在固定区域内拖拽目标

📅 2026/7/28 15:02:07
动画  实现在固定区域内拖拽目标
#动画 拖拽!DOCTYPE html html langen head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 meta http-equivX-UA-Compatible contentieedge titleDocument/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 classbox div classbox1/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