<style>
div {
width: 200px;
height: 200px;
position: absolute;
background-color: plum;
}
</style>
</head>
<body>
<div></div>
<script>
var div = document.querySelector("div");
div.onmousedown = function (e) {
var o = e || event;
var x = o.clientX - div.offsetLeft;
var y = o.clientY - div.offsetTop;
document.onmousemove = function (e) {
var o = e || event;
var left1 = o.clientX - x;
var top1 = o.clientY - y;
// document.documentElement.clientWidth(这个写法里面可以直接获得值)
var maxW = document.documentElement.clientWidth - div.offsetWidth;
var maxH = document.documentElement.clientHeight - div.offsetHeight;
if (left1 < 0) left1 = 0;
if (top1 < 0) top1 = 0;
if (left1 > maxW) { left1 = maxW };
if (top1 > maxH) { top1 = maxH };
div.style.left = left1 + "px";
div.style.top = top1 + "px";
}
}
// 给页面加 页面不卡顿
document.onmouseup = function () {
document.onmousemove = null;
}
</script>
</body>