如何在拖动到另一个元素(图片)时移除一个元素(图片) Drag'n'Drop 如何在拖动到大门时移除一个球(球的移动)请帮忙
var ball = document.getElementById("ball");
ball.onmousedown = function(e){
var coords = getCoords(ball);
shiftX = e.pageX - getCoords(ball).left;
shiftY = e.pageY - getCoords(ball).top;
ball.style.position = "absolute";
moveAt(e);
document.body.appendChild(ball);
ball.style.zIndex = 1000;
function moveAt(e) {
ball.style.left = e.pageX - shiftX + "px";
ball.style.top = e.pageY - shiftY + "px";
}
document.onmousemove =function (e) {
moveAt(e);
}
ball.onmouseup= function(){
document.onmousemove = null;
ball.onmouseup=null;
}
}
ball.ondragstart = function() {
return false;
};
function getCoords(elem) { // кроме IE8-
var box = elem.getBoundingClientRect();
return {
top: box.top + pageYOffset,
left: box.left + pageXOffset
};
}
<img src="https://isplit.ru/image/cache/data/brendy/Leco/street_plus_300_h_200_sm/street_plus_300_h_200_sm_1-630x630-0.jpg" alt="" srcset="" width="200" height="200">
<img src="https://st.depositphotos.com/1000459/2436/i/450/depositphotos_24366251-stock-photo-soccer-ball.jpg" alt="" srcset="" id="ball" width="100" height="100">
您的问题已通过常规检查解决,我们拥有解决问题的所有功能。我们需要确保当球击中球门时,我们将其移除,为此我们将使用事件
onmouseup,它会告诉我们何时释放球,然后我们将检查球是否击中球门区域,例如我们将计算这个 zone:var widthGoal = coordsGoal.top + goal.width, heightGoal = coordsGoal.left + goal.height;,这就是完成的代码:我添加了一个解决问题的选项(评论中讨论了随机定位的额外数量的球)。为了随机排列元素,我使用了'Math.random() * (max - min) + min'。一般来说,代码需要改进,因为有时会弹出一个错误,但我认为你会很有趣地弄清楚为什么,以及这一切是如何发生的。哦,是的,还有一件事,第一个球真的很糟糕,所以它静止不动,我想你会明白的。
在提出问题之前,我对您的建议是自己完成任务,否则一切都值得吗?祝你学习顺利。
编码:
评论的解决方案。(你能帮忙吗?如何添加,以便有几个球并且所有东西都可以移动?)
添加额外的球,结果:只需添加