<!DOCTYPE html>
<html>
<head>
<title>
</title>
<style media="screen" type="text/css">
*{
margin: 0;
padding: 0;
}
.box{
background: red;
width: 100px;
height: 100px;
position: absolute;
top: 0;
left: 100px;
}
</style>
</head>
<body>
<div class="box">
111
</div>
<div class="box" style="left:300px;top: 300px">
222
</div>
<div class="box" style="left:500px;top: 10px">
333
</div>
<script>
document.addEventListener("mousedown",drag);
document.addEventListener("mousemove",drag);
document.addEventListener("mouseup",drag);
var flag=false;
var x1,y1,stx,sty,el;
function drag(ev) {
var ev=ev || window.event;
ev.preventDefault();
switch(ev.type){
case "mousedown":
console.log(ev.target.className);
if(ev.target.className==='box'){
flag=true;
el=ev.target;
el.style.cursor="move";
el.style.zIndex='9';
//鼠标点中目标元素时鼠标在页面中的位置
x1=ev.clientX;
y1=ev.clientY;
// console.log('鼠标在页面上的位置'+x1);
//鼠标点中目标元素时元素的位置
// console.log('元素在页面中的横坐标位置'+el.offsetLeft)
stx=x1-el.offsetLeft;
sty=y1-el.offsetTop;
// console.log('鼠标在元素上的位置'+stx);
console.log('鼠标按下');
}
break;
case "mousemove":
if(flag){
x1=ev.clientX;
y1=ev.clientY;
var left,top;
left=x1-stx;
top=y1-sty;
if(left<0){
left=0;
}else if(left>window.innerWidth-el.offsetWidth){
left=window.innerWidth-el.offsetWidth;
}
if(top<0){
top=0;
}else if(top>window.innerHeight-el.offsetHeight){
top=window.innerHeight-el.offsetHeight;
}
el.style.left=left+'px';
el.style.top=top+'px';
}
break;
case "mouseup":
flag=false;
el.style.cursor="inherit";
console.log('鼠标抬起');
document.onmousemove = null;
document.onmouseup = null;
break;
}
}
</script>
</body>
</html>