六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 30|回复: 0

【JavaScript】画面元素(图片)可拖动的技术实现收藏

[复制链接]

升级  48%

6

主题

6

主题

6

主题

童生

Rank: 1

积分
24
 楼主| 发表于 2013-2-7 15:26:40 | 显示全部楼层 |阅读模式
这个关键是用好3个事件,一个是onmousedown一个是onmousemove一个是onmouseup
onmousedown记录当前鼠标所触发的对象,在onmousemove所触发的方法中进行移动,onmouseup放下拖动的对象。

代码:

<script language="javascript">  var checkMoving;  function divMove(){    checkMoving = false;    document.onmousedown=startMove;    document.onmousemove=moveObj;    document.onmouseup=new Function("checkMoving = false");  }  function startMove(){    if(event.srcElement.className!="imgObj") return;    checkMoving=true;    Xdiff=event.clientX-event.srcElement.style.pixelLeft;    Ydiff=event.clientY-event.srcElement.style.pixelTop;  }  function moveObj(){    if(!checkMoving) return true;    event.srcElement.style.pixelLeft=event.clientX-Xdiff;    event.srcElement.style.pixelTop=event.clientY-Ydiff;    return false;  }</script><body style="margin: auto;" ><div style="left:0;top:0;position:relative;overflow:hidden;width:100%;height:100%" id="div1"><img src="default.gif" style="position:relative;left:0px;top:0px;width:100px;height:100px;cursor:hand;" class=imgObj></div></body>
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表