<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#div1 {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<!-- return false;//火狐的bug当是空div的时候会出现半透明情况,也解决很多谷歌的bug
//IE6-8不能解决 -->
<span>fvnjdmmdmdmdmhfhhfhfhfhhfhf</span>
<br>
<div>djfkmjnvnd,s,s,,s,s</div>
<div id="div1">jdjjdjdjjgnnvikdkslal</div>
<script>
var div1 = document.getElementById('div1');
var disX=0;
var divY=0;
function mouseMove(ev){
var eve = window.ev || ev;
var l = eve.clientX - disX;
var t = eve.clientY - disY;
// l,t 是物体的位置
//当鼠标移动位置后 物体的位置=最新鼠标位置-相对位置距离
//左边当l<0物体 表示从左边拖出浏览器
if (l < 0) {
l = 0;
}//右边判断div的left>浏览器的可视区clientWidth-div的宽度,表示物体被拖出右边
else if (l > document.documentElement.clientWidth - div1.offsetWidth) {
l = document.documentElement.clientWidth - div1.offsetWidth;
}
if (t < 0) {
t = 0;
} else if (t > document.documentElement.clientHeight - div1.offsetHeight) {
t = ocument.documentElement.clientHeight - div1.offsetHeight;
}
div1.style.left = l + 'px';
div1.style.top = t + 'px';
}
function mouseUp() {
this.onmousemove = null;
this.onmouseup = null;
if(div1.releaseCapture){
div1.releaseCapture();
}//释放捕获 还能够获得其他文字
}
div1.onmousedown = function (ev) {
var eve = window.event || ev;
//当前鼠标在物体上 此时鼠标和物体的相对位置距离
disX = eve.clientX - div1.offsetLeft;
disY = eve.clientY - div1.offsetTop;
if (div1.setCapture) {
//IE下
div1.onmousemove = mouseMove;
//替换回div1解决IE问题
div1.onmouseup = mouseUp;
div1.setCapture();//捕获解决IE
return false;//火狐的bug当是空div的时候会出现半透明情况,也解决很多谷歌的bug
//IE6-8不能解决
} else {
document.onmousemove = mouseMove;
document.onmouseup = mouseUp;
return false;//火狐的bug当是空div的时候会出现半透明情况
}
}
</script>
</body>
</html>