如何通过拖动另一个图像来改变图像?

时间:2017-06-26 21:29:55

标签: javascript image function draggable

所以我试图通过拖动图片B将图片A更改为图片B.我只使用了一张图片,但我想让它与多张图片一起使用。This image kind of pictures what I want to do.

到目前为止我在JS中的所作所为:

function movePlayer1() {
    if (document.getElementById("pack")) {
        document.getElementById("spot1").src = "image/" + playerImg1;
    } else {
        document.getElementById("spot1").src = "image/" + playerImg2;
    }
}
document.querySelectorAll("img#spot1")[0].addEventListener("dragover", movePlayer1);
我是Javascript的新手,但我已经尝试了很多东西而无法弄清楚如何做到这一点,所以我希望有人可以帮助我。如果我需要提供任何额外信息,请告诉我们!

(当我将“playerImg2”拖到document.getElementById(“pack”)上时,它仍然会变为“playerImg1”而不是“playerImg2”。)

感谢。

1 个答案:

答案 0 :(得分:0)

为可投放区域使用背景图片
并使用图像的可拖动性:

const isClass = (cl, el) => el.classList.contains(cl);
const on = (typ, el, cb) => el.addEventListener(typ, cb);
let dragEl;

on("dragover",  document, (e) => e.preventDefault() );
on("dragend",   document, (e) => e.target.style.opacity = 1 );
on("dragstart", document, (e) => {
  dragEl = e.target;
  e.target.style.opacity = 0;
});
on("drop", document, (e) => {
  e.preventDefault();
  if(isClass("dropArea", e.target)) {
    dragEl.remove();
    e.target.append( dragEl );
  }
});
.dropArea {
  display:inline-block; vertical-align:middle;
  width: 57px; height: 87px; margin: 8px;
  background: url('https://i.stack.imgur.com/5nsDs.png') no-repeat 50% 50% / cover;
}
.dropArea.small{
  width:  30px; height: 40px;
}
.dropArea img{
  width: 100%; height: 100%;
  transition: 0.3s;
}
<div class="dropArea"><img src="https://i.stack.imgur.com/sBQ1c.png" draggable="true"></div>
<div class="dropArea"><img src="https://i.stack.imgur.com/kR6MI.png" draggable="true"></div>
<div class="dropArea"><img src="https://i.stack.imgur.com/XSBBq.png" draggable="true"></div>
<div class="dropArea small"></div>
<div class="dropArea small"></div>
<div class="dropArea small"></div>