如何获取div左上角的坐标

How to get coordinates of upper left corner of a div

我正在尝试获取父级 div 内可拖动 div 左上角的坐标。我可以在父 div 中获取鼠标坐标,这是通过 onmousemove 标记完成的。我想知道是否有任何类似的标签,例如 onmove 用于获取 div 的坐标。我使用的代码如下

<!DOCTYPE html>
<html>
        <style>
        #parent {
            width: 148mm;
            height: 160mm;
            background-color: yellow;
            position: relative;
            <!--border: 3px solid #e5e5e5;-->
            
        }
        #mydiv {
          position: absolute;
          z-index: 9;
          
          text-align: center;
          border: 1px solid #d3d3d3;
        }

        #mydivheader {
          padding: 10px;
          cursor: move;
          z-index: 10; 
        }
        </style>

        <body>
            <div id="parent" style="float:left" onmouseout="clearCoor()">
                <div id="mydiv">
                  <div id="mydivheader" onmove="showCoords(event)"><img src="bc.png" alt="image"></div>
                </div>
            </div>
            <p id="demo"></p>
        <script>
        //Make the DIV element draggagle:
        dragElement(document.getElementById("mydiv"));

        function dragElement(elmnt) {
          var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
          if (document.getElementById(elmnt.id + "header")) {
            /* if present, the header is where you move the DIV from:*/
            document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
          } else {
            /* otherwise, move the DIV from anywhere inside the DIV:*/
            elmnt.onmousedown = dragMouseDown;
          }

          function dragMouseDown(e) {
            e = e || window.event;
            e.preventDefault();
            // get the mouse cursor position at startup:
            pos3 = e.clientX;
            pos4 = e.clientY;
            document.onmouseup = closeDragElement;
            // call a function whenever the cursor moves:
            document.onmousemove = elementDrag;
          }

          function elementDrag(e) {
            e = e || window.event;
            e.preventDefault();
            // calculate the new cursor position:
            pos1 = pos3 - e.clientX;
            pos2 = pos4 - e.clientY;
            pos3 = e.clientX;
            pos4 = e.clientY;
            
            let parentElement = elmnt.parentElement;
            if(elmnt.offsetTop < 0){elmnt.style.top = "0px"; return;}
            if(elmnt.offsetTop > (parentElement.offsetHeight - elmnt.offsetHeight))     {
                elmnt.style.top = (parentElement.offsetHeight - elmnt.offsetHeight) + "px"; 
                return;
              }
            if(elmnt.offsetLeft < 0){elmnt.style.left = "0px";return}
            if(elmnt.offsetLeft > (parentElement.offsetWidth - elmnt.offsetWidth)){
                elmnt.style.left = (parentElement.offsetWidth - elmnt.offsetWidth) + "px";
                return;
            }
            
            // set the element's new position:
            elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
            elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
          }

          function closeDragElement() {
            /* stop moving when mouse button is released:*/
            document.onmouseup = null;
            document.onmousemove = null;
          }
        }

function showCoords(event) {
  var x = event.clientX;
  var y = event.clientY;
  var coor = "X coords: " + x + ", Y coords: " + y;
  document.getElementById("demo").innerHTML = coor;
}

function clearCoor() {
  document.getElementById("demo").innerHTML = "";
}

        </script>


        </body>
        
</html>

我使用了标签 onmove 但它没有用。

如果我理解正确,您希望在拖动时获取实际可拖动对象的坐标,那么也许 getBoundingClientRect 就是您想要的?

我修改了原始 HTML 以消除对元素 ID 的需求,因为当您开始将字符串连接到 ID 以标识元素时,事情有点误入歧途。还有其他更好的方法来识别 DOM 元素,也许最有用的是 querySelector and querySelectorAll,为了简洁起见,它们都在下面使用箭头函数以 shorthand 表示法编写。

getBoundingClientRect 函数也已缩写为 box,它在 showCoords 函数中称为 let obj=box(event.target);,其中 event.target 派生自外部注册的事件监听器,像这样:

q('.draggable > div').addEventListener('mousemove',showCoords); // the event is implicitly applied...

而不是 onmove 在这种情况下,您需要的事件实际上是 onmousemove - 在这里再次分配了外部侦听器而不是旧的内联类型 onmousemove=func(e)

const box=(n)=>n.getBoundingClientRect();
const q=(e,n=document)=>n.querySelector(e);
const qa=(e,n=document)=>n.querySelectorAll(e);



qa('.draggable').forEach(el=>dragElement(el));
q('.draggable > div').addEventListener('mousemove',showCoords);
q('.parent').addEventListener('mouseout',clearCoor);






function dragElement(n) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  let child=q('div',n);

  if ( child ) child.onmousedown = dragMouseDown;
  else n.onmousedown = dragMouseDown;

  
  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    pos3 = e.clientX;
    pos4 = e.clientY;

    document.onmouseup = closeDragElement;
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();

    
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;

    let parentElement = n.parentNode;
    if( n.offsetTop < 0 ){ n.style.top = "0px"; return; }
    
    if( n.offsetTop > ( parentElement.offsetHeight - n.offsetHeight ) ){
      n.style.top = (parentElement.offsetHeight - n.offsetHeight) + "px"; 
      return;
    }
    
    if( n.offsetLeft < 0 ){ n.style.left = "0px"; return }
    if( n.offsetLeft > ( parentElement.offsetWidth - n.offsetWidth ) ){
      n.style.left = ( parentElement.offsetWidth - n.offsetWidth ) + "px";
      return;
    }

    n.style.top = (n.offsetTop - pos2) + "px";
    n.style.left = (n.offsetLeft - pos1) + "px";
  }


  function closeDragElement() {
      document.onmouseup = null;
      document.onmousemove = null;
  }
}//close parent function `dragElement`


function showCoords(event) {
  let obj=box(event.target);
  
  let str=`
    X:${event.clientX}
    Y:${event.clientY}
    <br />
    Top-Left:${obj.top.toFixed(2)}px, ${obj.left.toFixed(2)}px
    Top-Right:${obj.top.toFixed(2)}px, ${obj.right.toFixed(2)}px
    <br />
    Bttm-Left:${obj.bottom.toFixed(2)}px, ${obj.left.toFixed(2)}px
    Bttm-Right:${obj.bottom.toFixed(2)}px, ${obj.right.toFixed(2)}px`;
  
  q("#demo").innerHTML = str;
}

function clearCoor() {
  q("#demo").innerHTML = "";
}
.parent{
  width: 148mm;
  height: 160mm;
  background-color: yellow;
  position: relative;
  border: 3px solid #e5e5e5;
}

.draggable{
  position: absolute;
  z-index: 9;
  text-align: center;
  border: 1px solid #d3d3d3;
}


.draggable > div{
  padding: 10px;
  cursor: move;
  z-index: 10; 
}

#demo{
  min-height:3rem;
  font-family:monospace;
  font-size:smaller;
}
<p id='demo'></p>

<div class='parent'>
  <div class='draggable'>
    <div>
      <img src='//placekitten.com/200/200?image=15' alt='image' />
    </div>
  </div>
</div>