<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.box {
position: absolute;
width: 300px;
height: 300px;
background-color: pink;
left: 0;
}
</style>
<script src="jquery/jquery-3.5.1.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="box"></div>
<script type="text/javascript">
$(function(){
$('.box').mousedown(function(event){
// 特别注意flag一定要在这里声明
let flag = true
// 获取页面的初始坐标
const startx = event.pageX
const starty = event.pageY
// 获取box的left和top数值
const l = $('.box').offset().left
const t = $('.box').offset().top
// 鼠标移动事件
$(document).mousemove(function(e){
if(flag)
{
const endx = e.pageX
const endy = e.pageY
s const left = endx - startx + l
const top = endy -starty +t
$('.box').css({
'left': left +'px',
'top': top + 'px'
})
}
}).mouseup(()=>{
flag = false
})
// 鼠标移动后鼠标弹起事件
})
})
</script>
</body>
</html>
1、首先下载jQuery
2、自己修改 src 的内容
3、代码如上