javascript - 用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;
}
解决方案
推荐阅读
- python-3.x - 如果另一个列表中的两个项目连续出现,如何将字符添加到列表中?Python
- c# - C# Selenium:缺少轮询间隔使条件失败
- c# - 我如何最小化这个 IRepository?
- ios - 存储共享 Safari 凭据时出现 SecAddSharedWebCredential 静默错误 - 应用审核失败
- html - 联系表格获取消息
- python - 基于Python中的对象键从列表中检索对象的元素
- python - “ValueError:需要超过 X 值来解包”迭代不完整元组的 Python 方式?
- c# - 在 WPF 文本框中启用拼写检查会减慢加载速度
- ios - 呼叫目录分机的呼叫者 ID 中的 UserDefaults
- f# - F#:为什么同时拥有 '::' 和 '@'