首页 > 代码库 > 实例:拖拽(面向对象)

实例:拖拽(面向对象)

<style>
  #div1 {width: 100px; height: 100px; background: red; position: absolute;};
</style>


<script>
  var oDiv = null;
  var disX = 0;
  var disY = 0;

  window.onload = function()
  {
    oDiv = document.getElementById(‘div1‘);

    oDiv.onmousedown = fnDown;
  };

  function fnDown(ev)
  {
    var oEvent = ev||event;
    disX = oEvent.clientX - oDiv.offsetLeft;
    disY = oEvent.clientY - oDiv.offsetTop;

    document.onmousemove = fnMove;

    document.onmouseup = fnUp;
  };

  function fnMove(ev)
  {
    var oEvent = ev||event;
    oDiv.style.left = oEvent.clientX-disX + ‘px‘;
    oDiv.style.top = oEvent.clientY-disY + ‘px‘;
  };

  function fnUp(ev)
  {
    document.onnousemove = null;
    document.onmouseup = null;
  };

</script>

<body>
  <div id="div1"></div>
</body>

实例:拖拽(面向对象)