javascript拖拽盒子移动的实现

来源:互联网 发布:手机简单编曲软件 编辑:程序博客网 时间:2024/05/21 10:31

原理比较简单,可以参照之前的文章javascript淘宝主图放大镜功能帮助理解。

<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">*{margin: 0;padding: 0;}#box{position: absolute;left: 50px;top: 50px;width: 200px;height: 200px;background: red;}#box2{position: relative;box-sizing: border-box;width: 800px;height: 400px;margin: 50px auto;border: 1px solid gray;}</style><script type="text/javascript">window.onload = function (){var box = document.getElementById('box');var box2 = document.getElementById('box2');var boxX = 0;var boxY = 0;box.onmousedown = function (ev){var ev = ev||event;boxX = ev.clientX - box.offsetLeft;boxY = ev.clientY - box.offsetTop;var n = 10;//吸附参数if(box.setCapture){document.onmousemove = mousemove;document.onmouseup = mouseup;box.setCapture();//IE中将其他地方的事件集中到box}else{document.onmousemove = mousemove;document.onmouseup = mouseup;}function mousemove (ev){var ev = ev||event;var l = ev.clientX - boxX;var t = ev.clientY - boxY;//边缘吸附处理if(l<n){l = 0;}else if(l>box2.offsetWidth-box.offsetWidth-n){l = box2.offsetWidth-box.offsetWidth-2;}if(t<n){t = 0;}else if(t>box2.offsetHeight-box.offsetHeight-n){t = box2.offsetHeight-box.offsetHeight-2;}box.style.left = l+"px";box.style.top = t+"px";}function mouseup (){this.onmousemove = null;this.onmouseup = null;if(this.releaseCapture){this.releaseCapture();}}return false;}}</script></head><body><div id="box2"><div id="box"></div></div></body></html>


1 0