1. 程式人生 > >js 滑鼠拖拽元素移動

js 滑鼠拖拽元素移動

<!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>