案例:限制范围的拖拽和磁性吸附
<body> <div id="div1"></div> <img src="1.jpg" id="img1"/> </body> <style> #div1 {width: 100px; height: 100px; background: red; position: absolute;} #img1 { position: absolute;} </style> <script> window.onload = function() { var oDiv = document.getElementById('div1'); var oImg = document.getElementById('img1'); drag(oImg); drag(oDiv); function drag(obj) { obj.onmousedown = function(ev) { var ev = ev || event; var disX = ev.clientX - this.offsetLeft; var disY = ev.clientY - this.offsetTop; if ( obj.setCapture ) { obj.setCapture(); } document.onmousemove = function(ev) { var ev = ev || event; var L = ev.clientX - disX; var T = ev.clientY - disY; if ( L < 0 ) { /* 若实现磁性吸附效果只需改为 L < 100 */ L = 0; } else if ( L > document.documentElement.clientWidth - obj.offsetWidth ) { L = document.documentElement.clientWidth - obj.offsetWidth; } if ( T < 0 ) { T = 0; } else if ( T > document.documentElement.clientHeight - obj.offsetHeight ) { T = document.documentElement.clientHeight - obj.offsetHeight; } obj.style.left = L + 'px'; obj.style.top = T + 'px'; } document.onmouseup = function() { document.onmousemove = document.onmouseup = null; if ( obj.releaseCapture ) { obj.releaseCapture(); } } return false; } } } </script>