簡體   English   中英

相對拖放位置

[英]Drag and drop position relative

為什么當您按下鼠標時球相對定位,它會反彈? 絕對定位是指這種情況不會發生的情況。

 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="" /> 

我猜是因為body元素的填充。 請解釋。

看來我找到了答案在JavaScript中相對定位的元素上實現拖放

就像它所說的, 相對位置,您的元素在其父標簽中包含所有對象的偏移量,並且在父對象的邊距填充中也包含偏移量,因此當您嘗試獲取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