如何将全局坐标转换为本地?

时间:2014-04-15 16:03:21

标签: javascript drag-and-drop

我创建了一些简单的拖放操作。 (代码中有一些似乎应该有用的垃圾。)

HTML:

<div id="container">
    <div id="target"></div>
</div>

使用Javascript:

   var el = document.getElementById('target');
   var mover = false,
       x, y, posx, posy, first = true;
   el.onmousedown = function () {
       mover = true;
   };
   document.onmouseup = function () {
       mover = false;
       first = false;
   };
   document.onmousemove = function (e) {
       if (mover) {
           e = e || window.event;
           var target = e.srcElement || e.target;

           var rect = target.getBoundingClientRect();
           if (first) {
               first = false;
               x = (getMouseCoordinates(e).x - rect.left);
               y = (getMouseCoordinates(e).y - rect.top);
           }

           posx = getMouseCoordinates(e).x;// - x;
           posy = getMouseCoordinates(e).y;// - y;

           el.style.left = posx + 'px';
           el.style.top = posy + 'px';
       }
   };


   function getMouseCoordinates(e) {
       e = e || window.event;

       var pageX = e.pageX;
       var pageY = e.pageY;
       if (pageX === undefined) {
           pageX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
           pageY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
       }

       return {
           x: pageX,
           y: pageY
       }
   }

CSS:

#target {
    left: 50px;
    top: 50px;
    width: 150px;
    height: 100px;
    background-color: #ffc;
    position: absolute;
}
#container {
    left: 30px;
    top:30px;
    width: 300px;
    height: 300px;
    background-color: red;
    position: absolute;
}

http://jsfiddle.net/YGzm6/

问题在于,draggable位于定位的容器内。因此,当我使用鼠标的全局坐标定位可拖动时,可拖动实际上相对于其非全局容器定位。

那么我如何翻译坐标,以便可拖动的人不会跳?当然我需要知道父容器的偏移量?

1 个答案:

答案 0 :(得分:0)

var x = 0, y = 0;
var element = document.getElementById('container');

do {
    x += element.offsetLeft;
    y += element.offsetTop;
}
while (element = element.offsetParent);