<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#box {
width: 300px;
height: 300px;
background: red;
position: absolute;
}
</style>
</head>
<body>
<div id="box">
快来托我吧
</div>
</body>
</html>
<script>
//引入
var box = document.getElementById("box");
//鼠标按下
box.onmousedown = function (e) {
var e = e || event;
var x = e.offsetX;
var y = e.offsetY;
//在文档页面上移动
document.onmousemove = function (e) {
var e = e || event;
var l = e.clientX - x;
var t = e.clientY - y;
//边界处理
var left = document.documentElement.clientWidth - 300;
var top = document.documentElement.clientHeight - 300;
l = l < 0 ? 0 : (l > left ? left : l);
t = t < 0 ? 0 : (t > top ? top : t);
box.style.left = l + "px"
box.style.top = t + "px";
//阻止默认行
return false;