<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 40px;
height: 40px;
background-color: pink;
font-size: 12px;
text-align: center;
line-height: 40px;
position: relative;
color: red;
}
</style>
</head>
<body>
<div>泡</div>
<script>
var x1 = 0, y1 = 0, div;
init()
function init() {
div = document.querySelector("div")
div.addEventListener("mousedown", mouseHandler);
}
function mouseHandler(e) {
if (e.type === "mousedown") {
x1 = e.offsetX;
y1 = e.offsetY;
document.addEventListener("mousemove", mouseHandler)
document.addEventListener("mouseup", mouseHandler)
} else if (e.type === "mousemove") {
div.style.left = e.clientX - x1 + "px";
div.style.top = e.clientY - y1 + "px";
} else if (e.type === "mouseup") {
document.removeEventListener("mousemove", mouseHandler)
document.removeEventListener("mouseup", mouseHandler)
}
}
</script>
</body>
</html>
最简单拖拽01
最新推荐文章于 2024-01-23 16:14:51 发布