拖拽是在前端开发中,经常用到的一种使得目标文件位移的效果。其核心事件是鼠标的三个事件,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