div实现拖动效果

先屡一下实现思路

1监听到鼠标点击下去的事件,

2.在此同时,获取鼠标在div的位置,即距离div 的 top,left 的距离,在移动的过程中保持这个值不变,从而实现拖动

3.监听到鼠标松开的时间,此时不在同步div与鼠标的相对位置

代码: 已测试 引用http://blog.csdn.net/mixi9760/article/details/52059047

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><div id="main" style="background-color: aqua;width: 100px;height: 100px;position: absolute;left: 50px;top: 50px"> <div id="title" style="height: 10px;width:100%;background-color: antiquewhite;position: absolute;left: 0px;top: 0px"></div> <div class="box"></div></div><script> function Mover(title) { this.obj = title; this.startx = 0; this.starty; this.startLeft; this.startTop; this.mainDiv = title.parentNode; var that = this; this.isDown = false; this.movedown = function (e) { e = e ? e : window.event; if (!window.captureEvents) { this.setCapture(); } //事件捕获仅支持ie// 函数功能:该函数在属于当前线程的指定窗口里设置鼠标捕获。一旦窗口捕获了鼠标,// 所有鼠标输入都针对该窗口,无论光标是否在窗口的边界内。同一时刻只能有一个窗口捕获鼠标。// 如果鼠标光标在另一个线程创建的窗口上,只有当鼠标键按下时系统才将鼠标输入指向指定的窗口。// 非ie浏览器 需要在document上设置事件 that.isDown = true; that.startx = e.clientX; that.starty = e.clientY; that.startLeft = parseInt(that.mainDiv.style.left); that.startTop = parseInt(that.mainDiv.style.top); } this.move = function (e) { e = e ? e : window.event; if (that.isDown) { that.mainDiv.style.left = e.clientX - (that.startx - that.startLeft) + "px"; that.mainDiv.style.top = e.clientY - (that.starty - that.startTop) + "px"; } } this.moveup = function () { that.isDown = false; if (!window.captureEvents) { this.releaseCapture(); } //事件捕获仅支持ie } this.obj.onmousedown = this.movedown; this.obj.onmousemove = this.move; this.obj.onmouseup = this.moveup; //非ie浏览器 document.addEventListener("mousemove", this.move, true); } var mover = new Mover(document.getElementById("title")); //写两个是为了解决 ie 和非ie 浏览器关于事件捕获 的兼容性问题</script></body></html>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值