首页 > 解决方案 > 用JS拖拽图片

问题描述

我想在我的窗口周围拖动多个图像。我可以用一张图片做到这一点,但更多它不起作用。我认为这是因为我动态创建 div 并且其余代码的 ID 未知,但我不知道如何解决该问题

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  // if present, the header is where you move the DIV from:
  elmnt.addEventListener("onmousedown", dragMouseDown);
}


function dragMouseDown(e) {
  e = e || window.event;
  e.preventDefault();
  // get the mouse cursor position at startup:
  pos3 = e.clientX;
  pos4 = e.clientY;
  document.onmouseup = closeDragElement;
  // call a function whenever the cursor moves:
  document.onmousemove = elementDrag;
}

function elementDrag(e) {
  e = e || window.event;
  e.preventDefault();
  // calculate the new cursor position:
  pos1 = pos3 - e.clientX;
  pos2 = pos4 - e.clientY;
  pos3 = e.clientX;
  pos4 = e.clientY;
  // set the element's new position:
  elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
  elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}

function closeDragElement() {
  // stop moving when mouse button is released:
  document.onmouseup = null;
  document.onmousemove = null;
}

const CreerPerso = document.getElementById('createPerso');
const body = document.querySelector('body');
CreerPerso.addEventListener("click", CreationPersonnage);


function CreationPersonnage() {
  const divImg = document.createElement('div');
  divImg.classList.add("imgPerso");

  divImg.innerHTML = "<img src='images/circle.png' />";
  body.appendChild(divImg);

  }
  //drag images Personnage
  dragElement(document.getElementById("imgPerso"));

这是我的 CSS,当我放置 position: absolute; 我只能创建一个图像

.imgPerso {
    position: relative;
    cursor: move;
}
 .imgPerso img {
     width: 100px;
     height: 100px;
 }

标签: javascriptcssimageelectron

解决方案


推荐阅读