jQuery implement dialog drag

Before, the project leader asked me to implement a fixed dialog box that can be dragged. I wrote a dialog box drag method based on the code found on the Internet. Today I will share my code. 

function moveDialog(moveHeadId, dialogId) {
   var dialog = $("#" + dialogId);
    var moveHead = $("#" + moveHeadId);
    moveHead.bind("mousedown",function (event) {
        var offset_x = dialog[0].offsetLeft;
        var offset_y = dialog[0].offsetTop;
        var mouse_x = event.pageX;
        var mouse_y = event.pageY;
        $(document).bind("mousemove", function (event) {
            var _x = event.pageX - mouse_x;
            var _y = event.pageY - mouse_y;
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();
            var dialogWidth = $("#" + dialogId).width();
            var dialogHeight = $("#" + dialogId).height();
            var now_x = offset_x + _x;
            //不超过左边界
            now_x = (now_x < 0 ? 0 : now_x);
            //不超过右边界
            now_x = (now_x > windowWidth - dialogWidth ? windowWidth - dialogWidth : now_x) + "px";
            var now_y = offset_y + _y;
            //不超过上边界
            now_y = (now_y < 0 ? 0 : now_y);
            //不超过下边界
            now_y = (now_y > windowHeight - dialogHeight ? windowHeight - dialogHeight : now_y) + "px";
            dialog.css({
                top: now_y,
                left: now_x
            })
        })
    });
    $(document).bind("mouseup", function (event) {
        $(this).unbind("mousemove");
    })
}

 

Published 34 original articles · received 1 · views 1946

Guess you like

Origin blog.csdn.net/qq_38974638/article/details/104753499