<!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>
</head>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 300px;
height: 200px;
border: solid 1px;
position: absolute;
border-radius: 10px;
}
.up {
width: 100%;
background-color: blueviolet;
height: 30px;
line-height: 30px;
color: aliceblue;
border-radius: 10px 10px 0 0;
}
.up p {
margin-left: 10px;
user-select: none;
}
.down {
width: 100%;
height: 170px;
background-color: red;
border-radius: 0 0 10px 10px;
}
</style>
<body>
<div class="box">
<div class="up">
<p>X</p>
</div>
<div class="down"></div>
</div>
</body>
<script>
window.onload = function move(box, upBox) {
var upBox = document.querySelector('.up')
var box = document.querySelector('.box')
upBox.onmousedown = function (e) {
e = e || window.event;
// 鼠标距离盒子边框
let upLeft = e.clientX - box.offsetLeft
let upTop = e.clientY - box.offsetTop
upBox.onmousemove = function (e) {
e = e || window.event;
let cX = e.clientX - upLeft
let cY = e.clientY - upTop
box.style.left = cX + "px"
box.style.top = cY + "px"
}
}
upBox.onmouseup = function () {
this.onmousedown = null;
this.onmousemove = null;
move(box, upBox);
}
upBox.onmouseout = function () {
this.onmousedown = null;
this.onmousemove = null;
move(box, upBox);
}
}
</script>
</html>
效果图: