实现div拖拽
2013-11-08 15:40 taozsay 阅读(307) 评论(0) 收藏 举报实现div拖拽需要三个重要的事件:
1、onmousedown-鼠标按下事件
2、onmousemove-鼠标移动事件
3、onmouseup-鼠标抬起事件
当鼠标移出浏览器后再回到浏览器内部时,会丢失对div的控制,需要再次按下鼠标移动div,为了改善这一小问题,代码中使用了setCapture和releaseCapture。
其中,setCapture方法是用于监视鼠标操作事件,即使鼠标移出浏览器照样能够捕捉到鼠标位置,当鼠标移回浏览器内部时,此时div依然跟随着鼠标移动;当然,releaseCapture方法就是释放对鼠标操作事件的监视。
直接上码:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>实现div拖拽</title> <style> html{background: #002433} body,div,p{margin:0;padding:0} #box{height:220px;width:200px;border:1px solid #02212D;position: absolute;left:0;background: #fff} #handler{height:30px;background:#ddd;cursor: move;} </style> </head> <body> <div id='box'> <p id='handler'></p> </div> </body> </html> <script> window.onload=function(){ new drag('box','handler',true); } function drag(){return this.init.apply(this,arguments)}; drag.prototype={ init: function(container,handler,isLimit){ this.o=document.getElementById(container); this.h=document.getElementById(handler); this._x=this._y=0; this.limit = isLimit; this._move=this.bind(this,this.move); this._end=this.bind(this,this.end); this.addEvent(this.h,'mousedown',this.bind(this,this.start)); }, start:function(e){ var ev = e || window.event; this._x = ev.clientX - this.o.offsetLeft; this._y = ev.clientY - this.o.offsetTop; this.addEvent(document,'mousemove',this._move); this.addEvent(document,'mouseup',this._end); ev.preventDefault && ev.preventDefault(); this.h.setCapture && this.h.setCapture(); }, move:function(e){ var ev = e || window.event, l= ev.clientX - this._x, t= ev.clientY - this._y; if(!!this.limit){ var maxX = document.documentElement.clientWidth - this.o.offsetWidth, maxY = document.documentElement.clientHeight - this.o.offsetHeight; l = l < 0 ? 0 : l; l = l > maxX ? maxX : l; t = t < 0 ? 0 : t; t = t >maxY ? maxY : t; } this.o.style.left = l +'px'; this.o.style.top = t +'px'; }, end:function(){ this.removeEvent(document,'mousemove',this._move); this.removeEvent(document,'mouseup',this._end); this.h.releaseCapture && this.h.releaseCapture(); }, addEvent:function(o,e,fn){ return o.attachEvent ? o.attachEvent('on'+e,fn) : o.addEventListener(e,fn,false); }, removeEvent:function(o,e,fn){ return o.detachEvent ? o.detachEvent('on'+e,fn):o.removeEventListener(e,fn,false); }, bind:function(o,fn){ return function(){ return fn.apply(o,arguments); } } } </script>
作者:taoz
出处:www.cnblogs.com/bigbrid
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
本文如对您有帮助,还请多帮 【推荐】 下此文。
如果喜欢我的文章,请关注我的公众号
浙公网安备 33010602011771号