jquery实现对话框拖动

之前项目组长让我实现一个固定的对话框可以拖动的效果,根据网上查到的代码自己写了一个对话框拖动方法,今天给大家分享一下我的代码。 

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");
    })
}
发布了34 篇原创文章 · 获赞 1 · 访问量 1946

猜你喜欢

转载自blog.csdn.net/qq_38974638/article/details/104753499