简体   繁体   中英

How to get Co-ordinates on onmouseup?

I have built a javascript application for dragging and dropping divs from one place to another in the same page. I have made the dragging part. I have the co-ordinates of the div(s) where I must drop the div but I am stuck at the part where I should introduce conditions for matching the divs at target zone. Basically the divs can be dropped above any of the divs but they must drop exactly above the target div if on onmouseup event I am anywhere close to that target div. I am thinking of assigning the top and left attribute of my dragged(onmousdown) div to the target div but I may be wrong.. Please guide my through this part. Here is the part where I need help:

function mouseUp(e)
{
    e = e || window.event;
    var mousePos = mouseCoords(e);
    var itemPosition = getPosition(id);
    //console.log("This is at: "+itemPosition);
    //console.log(mousePos);
    console.log(getPosition(id));
    for(var i=0;i<destination.length;i++)
    {
        var curTarget = destination[i];
        var targPos = getPosition(curTarget);
        var targWidth = parseInt(curTarget.offsetWidth); 
        var targHeight = parseInt(curTarget.offsetHeight);
        var temp = document.elementFromPoint(event.clientX, event.clientY);

    }


    id = null;
}

Here is the link to my code: jsfiddle The javascript part must be written inside of html to make it work properly

The question title is misleading, what you really seem to be having trouble with is finding the coordinates of the target divs. You're grabbing mouse coordinates just fine using clientX and clientY though you likely want to be using the pageX and pageY coordinates as they are relative to the rendered page and not the viewport (ie. window the user is looking at). 0,0 using the client coordinates will change as the user scrolls whereas the page coordinates will reference a particular spot on the webpage.

As for finding your drop divs you can use the method getClientBoundingRect on the element and use the top , right , bottom , and left properties on the returned object to determine if the pageX and pageY coordinates of the mouse are inside (or close to inside) the element.

Maybe there's a better way, but this is how I would do it.

function mouseUp(e){
  var targets = document.getElementsByClassName("drop_here");
  for(var i=0;i<targets.length;i++){
      var bounds = targets[i].getClientBoundingRect();
      var lenience  = 5;
      if(e.pageX < bounds.right + lenience &&
         e.pageX > bounds.left - lenience &&
         e.pageY < bounds.top - lenience &&
         e.pageY > bounds.bottom + lenience){
        //do my work here   
      }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM