简体   繁体   中英

Drag and drop position relative

Why when the ball is placed relative positioning when you press the mouse it bounces? Absolute positioning is when this doesn't happen.

 var ball = document.querySelector('.ball'); ball.onmousedown = function(event) { var shiftX = event.pageX - getCoords(this).left, shiftY = event.pageY - getCoords(this).top; this.style.position = 'relative'; this.zIndex = 10000; function move(event) { this.style.left = event.pageX - shiftX + 'px'; this.style.top = event.pageY - shiftY + 'px'; } move.call(this, event); document.onmousemove = function(event) { move.call(ball, event); }; this.onmouseup = function(event) { document.onmousemove = this.onmouseup = null; }; return false; }; ball.ondragstart = function() { return false; }; function getCoords(elem) { var box = elem.getBoundingClientRect(); return { top: box.top + window.pageYOffset, left: box.left + window.pageXOffset }; } 
 body { margin: 50px; } img { cursor: pointer; } 
 <img class="ball" src="https://js.cx/clipart/ball.svg" alt="" /> 

I guess it's because of the padding of the body element. Please explain.

it seems i found answer Implementing drag and drop on relatively positioned elements in JavaScript

and as it says, with relative position, your element contain offset of all objects in his parent-tag and parent's margin and padding too so when you try to get elemtn's position, you should count it's real offset in parent, see in my code example work with count index

 <html> <body> <div id=obj1 style="width:100px; height:100px; background:#000; position:relative; " ></div> <div id=obj2 style="width:100px; height:100px; background:#000; position:relative; " ></div> <div id=obj3 style="width:100px; height:100px; background:#000; position:relative; " ></div> <script> var dragObj, count=0; function set_drag_drop(obj) { if(count>0){ // count margins and divs offset // body{ margin:10px; } // height:100px; obj.adx = 10; obj.ady = 10 + (count*100) }else{ obj.adx = 0; obj.ady = 0; } count++; obj.onmousedown = function(e) { var rect = obj.getBoundingClientRect(); obj.dx = rect.left - e.clientX; obj.dy = rect.top - e.clientY; obj.isDown = true; dragObj = this; } obj.onmouseup = function(e) { obj.isDown = false; } document.onmousemove = function(e) { if(dragObj && dragObj.isDown) { dragObj.style.left = e.pageX -dragObj.adx+ dragObj.dx +"px"; dragObj.style.top = e.pageY -dragObj.ady+ dragObj.dy + "px"; } } } set_drag_drop(document.getElementById("obj1")); set_drag_drop(document.getElementById("obj2")); set_drag_drop(document.getElementById("obj3")); </script> </html> 

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