七空幻音LOGO

七空幻音

在标签内拖动元素的相对位置2016-09-02 05:16:46

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

以前写过拖动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库哦

1条评论登录后可见

用户头像
幻音い
咕了咕了咕了....

文章:125

收藏:3

查看更多
详细图片
载入中...