続・動かすやつ

http://storehouse.sakura.ne.jp/drag.html
動きがぎこちないなぁ…と思っていたら、mousemoveをハンドルするオブジェクトの問題だった。
documentのmousemoveをハンドルするようにしたら、もう少し軽快になった。

<html>
  <head>
    <script type="text/javascript">
function add_event(element, type, handler, flag) {
  function handler_wrapper(e) {
    e = e || event;
    return handler(e);
  }

  if (element.addEventListener) {
    element.addEventListener(type, handler_wrapper, flag);
  } else if (element.attachEvent) {
    element.attachEvent("on" + type, handler_wrapper);
  }
}

var draggable = (function() {
  var z_index = 0;
  var drag = null;

  add_event(document, 'mousemove', function(e) {
    if (drag) {
      drag(e);
      return false;
    }
  });

  add_event(document, 'mouseup', function(e) {
    if (drag) {
      drag = null;
      return false;
    }
  });

  return function(id) {
    var element = document.getElementById(id);
    element.style.zIndex = z_index++;

    add_event(element, 'mousedown', function(e) {
      var top = parseInt(element.style.top);
      var left = parseInt(element.style.left);
      var start_x = e.clientX;
      var start_y = e.clientY;
      element.style.zIndex = z_index++;

      drag = function(mousemove) {
        var offset_x = mousemove.clientX - start_x;
        var offset_y = mousemove.clientY - start_y;
        element.style.top = (top + offset_y) + 'px';
        element.style.left = (left + offset_x) + 'px';
      };

      return false;
    });
  }
})();
    </script>
  </head>
  <body>
    <!-- foo -->
    <div id="foo" style="width:100px; height:100px; position:absolute; top:100px; left:100px; background-color:red; cursor:move;">
      foo
    </div>
    <script type="text/javascript">
      draggable('foo');
    </script>

    <!-- bar -->
    <div id="bar" style="width:100px; height:100px; position:absolute; top:200px; left:200px; background-color:blue; cursor:move;">
      bar
    </div>
    <script type="text/javascript">
      draggable('bar');
    </script>

    <!-- zoo -->
    <div id="zoo" style="width:100px; height:100px; position:absolute; top:300px; left:300px; background-color:yellow; cursor:move;">
      zoo
    </div>
    <script type="text/javascript">
      draggable('zoo');
    </script>
  </body>
</html>