<!DOCTYPE html>
<html lang=\\\"en\\\">
<head>
<meta charset=\\\"UTF-8\\\">
<meta name=\\\"viewport\\\" content=\\\"width=device-width, initial-scale=1.0\\\">
<title>打造自定义拖拽功能:JavaScript元素拖动的方法封装</title>
</head>
<style>
.img {
position: relative;
}
</style>
<body>
<img id=\\\"demo\\\" onclick=\\\"move(this)\\\" src=\\\"./test.png\\\" class=\\\"img\\\">
</body>
<script>
function move(img) {
img.onmousedown = function (oEvent) {
oEvent.preventDefault();
distX = oEvent.clientX - img.offsetLeft;
distY = oEvent.clientY - img.offsetTop;
oldX = img.offsetLeft;
oldY = img.offsetTop;
img.style.cursor = \\\'move\\\';
//添加一些其它样式
document.onmousemove = function (oEvent) {
oEvent.preventDefault();
const x = oEvent.clientX - distX;
const y = oEvent.clientY - distY;
img.style.left = x + \\\'px\\\';
img.style.top = y + \\\'px\\\';
img.style.marginLeft = \\\'unset\\\';
//添加一些其它样式
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
img.style.cursor = \\\'unset\\\';
}
}
}
</script>
</html>
原创文章,作者:网络技术联盟站,如若转载,请注明出处:https://www.sudun.com/ask/49825.html