完整代码实例:
<!doctype html>
<html>
<head>
<style type="text/css">
#box{
position:fixed;
left:100px;
top:100px;
background-color:red;
width:300px;
height:200px;
}
#out{
height:2000px;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
<script>
$(document).ready(function(){
var drafting=false;
var offX,offY,mouseX,mouseY,winX,winY,x,y;
$("#box").mousedown(function(event){
event.stopPropagation();
drafting=true;
});
$(document).mousemove(function(event){
event.stopPropagation();
var e=event||window.event;
mouseX=e.pageX||e.clientX+$(document).scrollLeft();
mouseY=e.pageY||e.clientY+$(document).scrollTop();
winX=$("#box").offset().left-$(document).scrollLeft();
winY=$("#box").offset().top-$(document).scrollTop();
if(drafting==false){
offX=mouseX-winX;
offY=mouseY-winY;
}
x=mouseX-offX;
y=mouseY-offY;
$("#box").css({'left':x,'top':y});
});
$(document).mouseup(function(event){
event.stopPropagation();
drafting=false;
});
});
</script>
</head>
<body>
<div id="box"></div>
<div id="out"></div>
</body>
</html>