如何将全局坐标转换为局部坐标

How do I convert global coordinates to local?

本文关键字:坐标 转换 局部 全局      更新时间:2023-09-26

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

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/

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

那么,我该如何翻译坐标,使拖动的人不会跳来跳去呢?我肯定需要知道父容器的偏移量吗?

var x = 0, y = 0;
var element = document.getElementById('container');
do {
    x += element.offsetLeft;
    y += element.offsetTop;
}
while (element = element.offsetParent);