<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖拽效果</title> </head> <style> body { background: skyblue; } #wrap { margin: 50px auto; width: 400px; height: 400px; border: 8px #b1b8e0 solid; background: #e9eff8; position: relative; } #drag { width: 50px; height: 50px; border: 8px #eb651d; background: #9de4ec; position: absolute; top: 0; left: 0; } </style> <body> <div id="wrap"> <div id="drag"></div> </div> <!-- ================================================================================================================================= --> <script> var wrap = document.getElementById('wrap'); var drag = document.getElementById('drag'); drag.onmousedown = function(event){ var event = event || window.event;//后者为IE //clientX获取鼠标距左窗口的距离 //offsetLeft待移动对象的左外边距 //tmpX作用在待移动对象上的鼠标到待移动对象左边距的距离 var tmpX = event.clientX - drag.offsetLeft; var tmpY = event.clientY - drag.offsetTop; //取消默认行为 if(event.preventDefault){ event.preventDefault(); }else{ event.returnValue = false; } document.onmousemove = function(event){ var event = event || window.event; //endX移动后对象的左边到左窗口的距离 //clientWidth = width + padding //offsetWidth = width + padding + border //简单的说mouseX = 大框的宽度 -(小框的宽度+内外边距) var endX = event.clientX - tmpX; var endY = event.clientY - tmpY; var mouseX = wrap.clientWidth - drag.offsetWidth; var mouseY = wrap.clientHeight - drag.offsetHeight; if(endX >= mouseX){ endX = mouseX; } if(endX <= 0){ endX = 0; } if(endY >= mouseY){ endY = mouseY; } if(endY <= 0){ endY = 0; } drag.style.left = endX + 'px'; drag.style.top = endY + 'px'; } } //鼠标抬起时清空移动操作 document.onmouseup = function(){ document.onmousemove = null; } </script> </body> </html>
效果图: