简体   繁体   English

相对拖放位置

[英]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. 我猜是因为body元素的填充。 Please explain. 请解释。

it seems i found answer Implementing drag and drop on relatively positioned elements in JavaScript 看来我找到了答案在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 就像它所说的, 相对位置,您的元素在其父标签中包含所有对象的偏移量,并且在父对象的边距填充中也包含偏移量,因此当您尝试获取elemtn的位置时,您应该算出它在父对象中的实际偏移量,请参见我的代码示例使用计数索引

 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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