显示box在桌面拖拽,不超过浏览器边缘
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
200px;
height: 200px;
background-color: indianred;
position: absolute;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
var obox = document.querySelector(".box");
obox.onmousedown=function(eve){
var e= eve ||window.event;
var offsetX = e.clientX -obox.offsetLeft;
var offsetY = e.clientY - obox.offsetTop;
document.onmousemove=function(eve){
var e = eve || window.event;
var l = e.clientX - offsetX;
var t = e.clientY - offsetY;
if(l<=0){
l = 0;
}
var clientWidth = document.documentElement.clientWidth ||document.body.clientWidth;
if(l>=clientWidth-obox.offsetWidth){
l=clientWidth-obox.offsetWidth;
}
if(t<=0){
t=0;
}
var clientHeight = document.documentElement.clientHeight ||document.body.clientHeight;
if(t>=clientHeight-obox.offsetHeight){
t=clientHeight-obox.offsetHeight;
}
obox.style.left =l +"px";
obox.style.top = t+"px";
}
}
document.onmouseup = function(){
document.onmousemove = null
}
</script>
</html>