jquery简单的拖动效果

  1. <!DOCTYPE html>
  2. <html>
  3. <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
  4. <title>简单拖曵原理实例</title>
  5.     <style type=”text/css”>
  6.         #drag{width:400px;height:300px;background:url(http://upload.yxgz.cn/uploadfile/2009/0513/20090513052611873.jpg);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.     </script>
  43. </head>
  44. <body>
  45.     <div id=”drag”>
  46.         <h2>来拖动我啊</h2>
  47.     </div>
  48. </body>
  49. </html>

标签