分别是鼠标按下,鼠标移动和鼠标抬起
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jQuery/jquery-3.3.1.js"></script>
<style>
.dialog{
position:absolute;
left:100px;
top:50px;
width:200px;
}
.title{
background: #D7DEF0;
width:100%;
height:50px;
line-height: 50px;
text-align: center;
cursor:move;
}
.content{
background: #F0F0F0;
width:100%;
height: 200px;
}
</style>
</head>
<body>
<div id="dialog" class="dialog">
<div id="title" class="title">Title</div>
<div class="content"></div>
</div>
<script>
var isMouseDown = false;
var lastPoint = {};
$("#title").on("mousedown", function (e) {
isMouseDown = true;
lastPoint.x = e.pageX;
lastPoint.y = e.pageY;
}).on("mousemove",function (e) {
//下面的这个if也是非常关键的哈!
if(isMouseDown){
var dialog = $("#dialog");
var targetX = parseInt(dialog.css("left")) + e.pageX - lastPoint.x; //e.pageX - lastPoint.x就是移动的距离,你好好理解一下哈
var targetY = parseInt(dialog.css("top")) + e.pageY - lastPoint.y;
dialog.css("left", targetX + "px");
dialog.css("top", targetY + "px");
lastPoint.x = e.pageX;
lastPoint.y = e.pageY;
}
}).on("mouseup",function (e) {
isMouseDown = false;
lastPoint = {};
})
</script>
</body>
</html>
实现的效果是这样的: