可拖动图层
1 <!DOCTYPE html> 2 <html> 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 4 <title>利用jquery实现简单拖曵原理实例 by js.alixixi.com</title> 5 <style type="text/css"> 6 #drag{width:400px;height:300px;background:url(<a href="http://upload.yxgz.cn/uploadfile/2009/0513/20090513052611873.jpg" target="_blank">http://upload.yxgz.cn/uploadfile/2009/0513/20090513052611873.jpg</a>);cursor:move;position:absolute;top:100px;left:100px;border:solid 1px #ccc;} 7 h2{color:#fff;background: none repeat scroll 0 0 rgba(16, 90, 31, 0.7);color:#FFFFFF;height:40px;line-height:40px;margin:0;} 8 </style> 9 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> 10 <script type="text/javascript"> 11 $(function(){ 12 /*--------------拖曳效果---------------- 13 *原理:标记拖曳状态dragging ,坐标位置iX, iY 14 * mousedown:fn(){dragging = true, 记录起始坐标位置,设置鼠标捕获} 15 * mouseover:fn(){判断如果dragging = true, 则当前坐标位置 - 记录起始坐标位置,绝对定位的元素获得差值} 16 * mouseup:fn(){dragging = false, 释放鼠标捕获,防止冒泡} 17 */ 18 var dragging = false; 19 var iX, iY; 20 $("#drag").mousedown(function(e) { 21 dragging = true; 22 iX = e.clientX - this.offsetLeft; 23 iY = e.clientY - this.offsetTop; 24 this.setCapture && this.setCapture(); 25 return false; 26 }); 27 document.onmousemove = function(e) { 28 if (dragging) { 29 var e = e || window.event; 30 var oX = e.clientX - iX; 31 var oY = e.clientY - iY; 32 $("#drag").css({"left":oX + "px", "top":oY + "px"}); 33 return false; 34 } 35 }; 36 $(document).mouseup(function(e) { 37 dragging = false; 38 $("#drag")[0].releaseCapture(); 39 e.cancelBubble = true; 40 }) 41 42 }) 43 44 </script> 45 </head> 46 47 <body> 48 <div id="drag"> 49 <h2>来拖动我啊</h2> 50 </div> 51 </body> 52 </html>
Javascript 事件捕获的备忘(setCapture,captureEvents)
object.setCapture() 当一个object的被 setCapture 后,他的方法将会被继承到整个文档进行捕获。
当不需要把方法继承到整个文档捕获时,要用 object.releaseCapture();
Mozilla 也有类似的功能,方法稍微不同
window.captureEvents(Event.eventType)
window.releaseEvents(Event.eventType)
Event 是Mozilla特殊的一个object.
eventType 包括: Abort, Blur, Click, Change, DblClick, DragDrop, Error, Focus, KeyDown, KeyPress, KeyUp, Load, MouseDown, MouseMove, MouseOut, MouseOver, MouseUp, Move, Reset, Resize, Select, Submit, Unload.