鼠标拖移对象

昨天在某位大仙博客上看到他在BS那些前端水平差的浮燥人士,BS那些“连用原生JS写拖放效果的能力都没有的人”。怕被BS,这里小写一个拖放效果练习一下。。。这里贴出代码:

js/move.js 文件

//将一个绝对定位的对象封装成可拖动对象
function MoveControl(c){
/* 考虑浏览器兼容性,这里编写一个获取事件对象的公共方法 */
c.getEvent=function(e){
if(!e){
e=event;
e.pageX=event.x;
e.pageY=event.y;
}
return e;
}
/* 当鼠标在该对象上按下,记录按下时鼠标的位置,并且修改监听锁,开始监听 */
c.onmousedown=function(e){
e=this.getEvent(e);
this.IX=e.pageX;
this.IY=e.pageY;
this.moveKey=true;
}
/* 当鼠标在对象上移动时,同时移动该对象 */
c.onmousemove=function(e){
if(!this.moveKey) return;

e=this.getEvent(e);
this.style.top=parseInt(this.style.top?this.style.top:0)+(e.pageY-this.IY)+"px";
this.style.left=parseInt(this.style.left?this.style.left:0)+(e.pageX-this.IX)+"px";
this.IX=e.pageX;
this.IY=e.pageY;
}
/* 当鼠标在对象上松开时,停止移动该对象 */
c.onmouseup=function(e){
this.moveKey=false;
}
}

HTML文件 child.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>无标题文档</title>
<script src="js/move.js"></script>
<script type="text/javascript">
window.onload
=function(){
var d = document.getElementById("d");
MoveControl(d);
}
</script>
</head>
<body>

<div id="d" style="width:100px; height:100px; background:#555; position:fixed;"></div>

</body>
</html>


OVER...

非常简单,下面看看效果:

IE8里:

 


 chrome里:

posted @ 2011-11-16 09:39  小浩叔叔  阅读(473)  评论(0编辑  收藏  举报