<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
#box{
height: 100px;
width: 100px;
background:red;
position: absolute;
cursor:move;
}
</style>
</head>
<body>
<div id="box">
</div>
</body>
</html>
<script>
var oBox = document.querySelector("#box");
oBox.onmousedown = function(evt){
var e = evt || event;
var offsetX = e.offsetX;
var offsetY = e.offsetY;
document.onmousemove = function(evt){
var e = evt || event;
var x = e.pageX - offsetX;
var y = e.pageY - offsetY;
if(x<0){
x = 0;
}
var maxLeft = window.innerWidth - oBox.offsetWidth;
if(x > maxLeft){
x = maxLeft;
}
if(y<0){
y = 0;
}
var maxTop = window.innerHeight - oBox.offsetHeight;
if(y > maxTop){
y = maxTop;
}
oBox.style.left = x + "px";
oBox.style.top = y + "px";
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
</script>
原文地址:https://www.cnblogs.com/fengzhi/p/12069970.html