鼠标拖曳效果

(为什么当设mousedown,mousemove都绑定在同一个对象时(img),鼠标释放时,物体仍会随着移动,当鼠标再点击一次时,物体才停止移动。而当mousedown,mousemove绑定在不同的对象时,则运行正常。)

求解决,谢谢~~~

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>无标题文档</title>

<style type="text/css">

*{

margin:0px;

padding:0px;}

#box{

width:400px;

height:466px;

overflow:hidden;

position:absolute;

border:4px solid #000000;

}

#nav{

background:#6DE9E3;

cursor:move;

}

</style>


<script>

window.onload=function (){

var nav=document.getElementById("nav");

var box=document.getElementById("box");

var img=document.getElementById("img3");

img.onmousedown=function(e){

e=e || window.event;

img.style.position='relative';

var divX=e.clientX-img.offsetLeft;

var divY=e.clientY-img.offsetTop;

startMove(divX,divY);

}

function startMove(divX,divY){

document.onmousemove=function(e){

e=e || window.event;

var l=e.clientX-divX;

var t=e.clientY-divY;

img.style.left=l+'px';

img.style.top=t+'px';

}

document.onmouseup=function(){

  document.onmousemove=null;

  document.onmouseup=null;

  }

}


}

</script>

</head>


<body>

<div id="box"><div id="nav">nav</div><img src="img3.jpg" id="img3"></div>

</body>

</html>


LOopz_
浏览 1059回答 1
1回答

Lemon156

onmousemove是绑定在document上的也就是说鼠标在页面上移动时图片就能跟着移动,但onmousemove调用的函数的参数是event,也就是当前事件,而startMove函数是在onmousedown里调用的,所以当前事件也就是鼠标点下的这个事件,这样就实现点下图片能拖曳图片的效果,如果你把onmousemove和onmousedown绑定同一个对象时,当你点下图片的时候,你会发现只有鼠标经过图片时图片才会随鼠标移动,而当鼠标不经过图片时,图片也就停止移动,而且你会发现,onmouseover调用的函数所传参数根本就没什么意义,这就是为什么不会出现拖曳效果了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript