JS实现简单的拖拽效果
摘要:实现代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div class="drop">拖动我</div></body></html><!--autointro-->...
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="drop">拖动我</div>
</body>
<script>
const dropEl = document.querySelector(".drop");
let offsetX, offsetY;
let isDroping = false;
dropEl.addEventListener("mousedown", (e) => {
let clineX = e.clientX,
clineY = e.clientY;
offsetX = clineX - dropEl.getBoundingClientRect().left;
offsetY = clineY - dropEl.getBoundingClientRect().top;
isDroping = true;
dropEl.style.cursor = "grabbing";
});
document.addEventListener("mousemove", (e) => {
if (isDroping) {
const newX = e.clientX - offsetX;
const newY = e.clientY - offsetY;
dropEl.style.left = newX + "px";
dropEl.style.top = newY + "px";
}
});
document.addEventListener("mouseup", () => {
isDroping = false;
dropEl.style.cursor = "grab";
});
</script>
<style>
:root {
--widthSize: 200px;
}
.drop {
width: var(--widthSize);
height: var(--widthSize);
text-align: center;
background: orange;
line-height: var(--widthSize);
padding: 20px;
margin: 20px;
user-select: none;
position: relative;
}
</style>
</html>
本文链接:https://blog.smallhao.fun/?id=20 转载需授权!
Chen’Blog版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!