JQuery实现DIV拖动效果

来源:互联网 发布:mac办公软件在哪里 编辑:程序博客网 时间:2024/05/16 08:05

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;
            });

0 0
原创粉丝点击