How to auto-center jQuery UI dialog when resizing browser?

前端 未结 6 1266
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 07:44

When you use jquery UI dialog, all works well, except for one thing. When the browser is resized, the dialog just stays in it\'s initial position which can be really annoyin

6条回答
  •  生来不讨喜
    2020-12-04 08:34

    A more comprehensive answer, which uses Nick's answer in a more flexible way can be found here.

    An adaption of the code of relevance from that thread is below. This extension essentially creates a new dialog setting called autoReposition which accepts a true or false. The code as written defaults the option to true. Put this into a .js file in your project so that your pages can leverage it.

        $.ui.dialog.prototype.options.autoReposition = true;
        $(window).resize(function () {
            $(".ui-dialog-content:visible").each(function () {
                if ($(this).dialog('option', 'autoReposition')) {
                    $(this).dialog('option', 'position', $(this).dialog('option', 'position'));
                }
            });
        });
    

    This allows you to supply a "true" or "false" for this new setting when you create your dialog on your page.

    $(function() {
        $('#divModalDialog').dialog({
            autoOpen: false,
            modal: true,
            draggable: false,
            resizable: false,
            width: 435,
            height: 200,
            dialogClass: "loadingDialog",
            autoReposition: true,    //This is the new autoReposition setting
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                }
            }
        });
    });
    

    Now this dialog will always reposition itself. AutoReposition (or whatever you call the setting) can handle any dialogs that do not have a default position and automatically reposition them when the window resizes. Since you're setting this when you create the dialog, you don't need to identify a dialog somehow because the repositioning functionality becomes built into the dialog itself. And the best part is that since this is set per dialog, you can have some dialogs reposition themselves and others remain where they are.

    Credit to user scott.gonzalez on the jQuery forums for the complete solution.

提交回复
热议问题