Implementing Drag And Drop On Relatively Positioned Elements In Javascript
Solution 1:
There are two separate issues to consider here:
- How can I get the position of an element on the page?
- What happens when I assign new values to the
left
andtop
style properties?
The answer to the first question relies on an understanding of element.offsetLeft
and element.offsetTop
. These properties give the offset relative to element.offsetParent
which is defined as "the closest (nearest in the containment hierarchy) positioned containing element".
In your document this is the <body>
element, so it works as you expected. If you were to place your squares inside other elements you'd find that your code would stop working. What you'd need is a function to walk up the tree of containing elements and sum each of the offsets, like this:
functionfindPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
}
Used like this:
var pos= findPos(element);
posX = event.clientX - pos.x;
posY = event.clientY - pos.y;
Answering the second question requires an understanding of relatively positioned elements. Elements that are positioned relatively appear in a position relative to where they would normally appear on the page. When you assign values to top
and left
you're not giving absolute values. You're giving positions that are treated as relative to the element's original position in the layout. This is a feature of relative positioning, not a bug. You probably want to use position: absolute;
instead.
Solution 2:
if you're using relative positioning somewhere, then the element's offset may not be relative to the top-left of the document.
you need to find the absolute offset of the element.
Post a Comment for "Implementing Drag And Drop On Relatively Positioned Elements In Javascript"