拖拽是在前端开发中,经常用到的一种使得目标文件位移的效果。其核心事件是鼠标的三个事件,mousedown(),mousemove(),mouseup(),通过改变目标绝对定位div的位置来实现拖动。
这里分享我的代码,希望得到大神的指点。
在文章的最后,将提供免费的代码资源,供和我一样的菜鸟学习。
HTML:
<div class="Pparent">
<div class="parent">
<span id="drag">点击移动</span>
</div>
</div>
CSS:
*{margin: 0;padding: 0;}
.Pparent{width: 1200px;height: 500px;margin: 100px auto 0;background: #454545;position: relative;}
.parent{width: 100px;height: 100px;background: cyan;position: absolute;}
.parent>span{width: 100%;height: 20px;display:block;text-align: center;cursor: move;background: pink}
JS:
$(function(){
function setDrag(id){
var that = $(id),
Parthis = that.parent(),//
Pparthis = Parthis.parent(),
startX = 0,
startY = 0,
lastX = 0,
lastY = 0,
drag ={
down:function(e){
startX = e.clientX - Parthis.position().left;
startY = e.clientY - Parthis.position().top;
this.setCapture && this.setCapture();//避免IE下拖拽过快鼠标失去对象
Pparthis.on('mousemove',drag.move);
Pparthis.on('mouseup',drag.up);
return false;
},
move:function(e){
lastX = e.clientX - startX;
lastY = e.clientY - startY;
var maxX = Pparthis.width()-Parthis.outerWidth();//最大值
var maxY = Pparthis.height()-Parthis.outerHeight();
lastX = lastX<0 ? 0:lastX;//根据最大值求范围
lastX = lastX>maxX ? maxX:lastX;
lastY = lastY<0 ? 0:lastY;
lastY = lastY>maxY ? maxY:lastY;
Parthis.css({'left':lastX+'px','top':lastY+'px'});
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); // 防止拖动文本
e.stopPropagation();
},
up:function(){
Pparthis.off('mousemove',drag.move);//移除on绑定的方法
Pparthis.off('mouseup',drag.up);
}
};
that.on('mousedown',drag.down);
}
setDrag("#drag");
});
源文件下载: http://download.csdn.net/detail/u014703834/8244347