<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>拖拽图片</title>
</head>
<body>
<img id="img" src="./icon.jpg" alt="" width="40" />
</body>
<script>
var checkImg = document.getElementById("img");
checkImg.onmousedown = function (e) {
// 取消默认事件
e.preventDefault ? e.preventDefault() : e.returnValue == false;
// 创建src标签
var src = this.getAttribute("src");
var img = document.createElement("img");
img.setAttribute("src", src);
img.style.width = "40px";
img.style.position = "absolute";
img.style.top = this.offsetTop + "px";
img.style.left = this.offsetLeft + "px";
img.style.cursor = "move";
document.body.appendChild(img);
document.onmousemove = function (e) {
// 动态赋值坐标点
e = e || window.event;
img.style.top = e.clientY - img.offsetHeight / 2 + "px";
img.style.left = e.clientX - img.offsetWidth / 2 + "px";
};
document.onmouseup = function (e) {
img.style.cursor = "default";
document.onmousemove = document.onmouseup = null;
// 鼠标坐标信息
console.log({
x: Number(img.style.left.slice(0, -2)) + img.offsetWidth / 2,
y: Number(img.style.top.slice(0, -2)) + img.offsetHeight / 2,
});
};
};
</script>
</html>
图片拖拽效果
最新推荐文章于 2022-07-07 23:41:24 发布