温馨提示: 这篇文章于2792天前编写,现在可能不再适用或落后.

由于每次我自己都要忘记这个东西,所以我还是记录下来比较好。趁现在记得着..

以前写过拖动div的效果,那个是对于文档父类的,只需要绝对定位坐标就可以拖动,这次写的是对于窗口的相对坐标拖动。

这图有毒..

<style>
        *{
            margin:0;
            padding:0;
        }
        #warp{
            background-color:#00a0d2;
            width:400px;
            height:400px;
            margin:50px 100px;
            position:relative;
        }
        #move{
            width:50px;
            height:50px;
            background-color: #18cb2e;
            position:absolute;
            cursor:grab;
        }
    </style>
<div id="warp">
    <div id="move">

    </div>
</div>

```

<script> $(function(){ $("#move").mousedown(function(e){ var offset = $(this).offset();//获取offset信息 //使用event属性获取鼠标离文档左侧距离减去元素左侧距离距离,y则为文档上方 var x = e.clientX - offset.left; var y = e.clientY - offset.top; //绑定移动事件 $("#warp").bind("mousemove",function(ev){ //停止浏览器默认事件 $(this).stop(); //同样获取当前移动的元素offset信息 var offsets = $(this).offset(), move_x = ev.clientX - x,//这里减去鼠标按下获取的x值 move_y = ev.clientY - y,//同样 //上面2步的意思是让在拖动的时候鼠标不会瞬间移动(违和感) //获取相对位置 xx = move_x-offsets.left, yy = move_y-offsets.top, w = $(this).width()-$("#move").width(),//计算最大x h = $(this).height()-$("#move").height();//计算最大y if(xx<=0||yy<=0||xx>w||yy>h){//判断是否在warp里面移动 return false; } //设置元素位置 $("#move").css({left:xx+"px",top:yy+"px"},0); }); }); //解除绑定 $(document).mouseup(function(){ $("#warp").unbind("mousemove"); }) }) </script>

```   解释全在注释里面,别忘记导入jq库哦

    阁下需要登录后才可以查看评论哦~

    随便看看

      载入中...

      正在准备穿越次元,阁下请稍等片刻~