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="" />
我想這是因爲身體元素的填充。請解釋。
[實施拖動和在JavaScript中滴上相對定位元素]的可能的複製(http://stackoverflow.com/questions/5111492/implementing-drag-and-drop-on-relatively-positioned -elements-中的JavaScript) – LGSon