鼠标拖拽js

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>鼠标拖拽</title>
  <script type="text/javascript">
   function Drag(o, e){
    var e = window.event || e;
    var _x = e.offsetX || e.layerX;
    var _y = e.offsetY || e.layerY;
    o.style.filter = 'Alpha(opacity=70)';
    o.style.opacity = '0.7';
    document.onmousemove = function(e){
     var e = window.event || e;
     alert(_x + ", " + _y + "\r\n" + e.clientX + ", " + e.clientY + "\r\n" + e.offsetX + ", " + e.offsetY);
     o.style.left = e.clientX - _x + 'px';
     o.style.top = e.clientY - _y + 'px';
     o.style.cursor="move";
    }
    document.onmouseup = function(e){
     document.onmousemove = null;
     o.style.filter = o.style.opacity = '';
     o.style.cursor="default";
    }
   }
  </script>
 </head>
 <body>
  <div onmousedown="Drag(this, event)"
   style="position: absolute; border: 1px solid red; background: pink; width: 400px; height: 300px;"></div>
 </body>
</html>
绿色字体处: _x, _y已经形成闭包, 是不会变的, 值为最初始鼠标相对其DIV原点(0,0)的距离

蓝色字体处: e.clientX, e.clientY为鼠标相对屏幕的原点(0,0)的距离

粉色字体处: document.onmouseup和document.onmousemove这两个事件被设定在drag事件中才产生,这样的好处是在其他情况下不会产生拖放的效果

红色字体处: document.onmousemove在onmouseup事件中清除是为了善后工作, 这点要注意

你可能感兴趣的:(鼠标拖拽js)