1.指定div的Id<div id="drag">
<h2>来拖动我啊</h2>
</div>
2.注册监听mousedown事件
var dragging = false;
var iX, iY;
//鼠标按下
$("#drag").mousedown(function(e) {
dragging = true;//鼠标按下可移动
iX = e.clientX - this.offsetLeft;//横坐标
iY = e.clientY - this.offsetTop;//竖坐标
this.setCapture && this.setCapture();//设置鼠标捕获
return false;
});
3.注册监听onmousemove事件
//鼠标移动
document.onmousemove = function(e) {
if (dragging) {//鼠标移动
var e = e || window.event;
var oX = e.clientX - iX;
var oY = e.clientY - iY;
$("#drag").css({"left":oX + "px", "top":oY + "px"});//使用样式定位
return false;
}
};
4.注册监听mouseup//鼠标释放
$(document).mouseup(function(e) {
dragging = false;
$("#drag")[0].releaseCapture();
e.cancelBubble = true;
});