2016-01-21 207 views
0

爲什麼當球被放置時相對定位當你按下鼠標時會彈跳?絕對定位是在沒有發生的情況下。拖放相對位置

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

我想這是因爲身體元素的填充。請解釋。

+0

[實施拖動和在JavaScript中滴上相對定位元素]的可能的複製(http://stackoverflow.com/questions/5111492/implementing-drag-and-drop-on-relatively-positioned -elements-中的JavaScript) – LGSon

回答

0

看來我找到答案 Implementing drag and drop on relatively positioned elements in JavaScript

和它說,與相對位置,你的元素包含抵消了他的父標籤 和家長的保證金填充所有物體的太 因此當您嘗試獲取elemtn的位置時,您應該將其計算在父代中的實際偏移量,請參閱我的代碼示例中的工作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) 
 
{ 
 
\t if(count>0){ 
 
\t \t // count margins and divs offset 
 
\t \t // body{ margin:10px; } 
 
\t \t // height:100px; 
 
\t \t obj.adx = 10; 
 
\t \t obj.ady = 10 + (count*100) 
 
\t }else{ 
 
\t \t obj.adx = 0; 
 
\t \t obj.ady = 0; 
 
\t } 
 
\t count++; 
 
\t 
 
\t obj.onmousedown = function(e) 
 
\t { 
 
\t \t var rect = obj.getBoundingClientRect(); 
 
\t \t obj.dx = rect.left - e.clientX; 
 
\t \t obj.dy = rect.top - e.clientY; 
 
\t \t obj.isDown = true; 
 
\t \t dragObj = this; 
 
\t } 
 

 
\t obj.onmouseup = function(e) 
 
\t { 
 
\t \t obj.isDown = false; 
 
\t } 
 

 
\t document.onmousemove = function(e) 
 
\t { 
 
\t \t if(dragObj && dragObj.isDown) 
 
\t \t { 
 
\t \t \t dragObj.style.left = e.pageX -dragObj.adx+ dragObj.dx +"px"; 
 
\t \t \t dragObj.style.top = e.pageY -dragObj.ady+ dragObj.dy + "px"; 
 
\t \t } 
 
\t } 
 
} 
 

 
set_drag_drop(document.getElementById("obj1")); 
 
set_drag_drop(document.getElementById("obj2")); 
 
set_drag_drop(document.getElementById("obj3")); 
 

 
</script> 
 
</html>