<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽</title>
<script src="js/jquery-3.4.1.min.js"></script>
<script>
$(function(){
//为标签添加鼠标按下事件
$("div").mousedown(function(e){
// 当鼠标按下,获取鼠标位置
var mouseOldX = e.pageX;
var mouseOldY = e.pageY;
// 为鼠标添加移动事件
$(this).on("mousemove",function(e){
// 当鼠标运动时获取鼠标的位置
var mouseNewX = e.pageX;
var mouseNewY = e.pageY;
// 计算鼠标移动的距离
var moveX = mouseNewX - mouseOldX;//x移动的距离
var moveY = mouseNewY - mouseOldY;//y移动的距离
//将新的鼠标位置保存
mouseOldX = mouseNewX;
mouseOldY = mouseNewY;
//将标签位置按照鼠标移动的距离进行移动
var divOldXY = $(this).offset();
$(this).offset({
left:divOldXY.left + moveX,
top:divOldXY.top + moveY
})
//为鼠标添加抬起事件
$(this).on("mouseup mouseout",function(){
// 清除当前标签的鼠标移动事件
$(this).off("mousemove");
});
});
})
});
</script>
<style>
body{
margin: 0;
}
div{
height: 100px;
width: 100px;
background-color: red;
top: 0;
left: 0;
position: absolute;
}
</style>
</head>
<body>
<div></div>
</body>
</html>