jQuery: Set modal dialog overlay color

橙三吉。 提交于 2019-11-29 01:05:21
mohitp

You can use the open and close events of the ui-dialog.

$("#your-dialog").dialog(
{
    autoOpen: false, 
    modal: true, 
    open: function() {
        $('.ui-widget-overlay').addClass('custom-overlay');
    }          
});

And add the required styling in the CSS. Example:

.ui-widget-overlay.custom-overlay
{
    background-color: black;
    background-image: none;
    opacity: 0.9;
    z-index: 1040;    
}

The overlay element is an immediate sibling of the dialog widget and exposes the ui-widget-overlay class, so you can match it and modify the background color on a per-dialog basis:

$("#yourDialog").dialog("widget")
                .next(".ui-widget-overlay")
                .css("background", "#f00ba2");

You can see the results in this fiddle.

The background of the JQuery dialog is a div that has the class "ui-widget-overlay". The key styles you want to adjust is "opacity", "filter" and "background-color" ("opacity" and "filter" are two different ways of setting opacity for the different browsers.) You can either adjust the class definition or do the following in the dialog definition:

$("div#MyDialog").dialog({
    title: "My Dialog Title",
    open: function (event, ui) {
        $(".ui-widget-overlay").css({
            opacity: 1.0,
            filter: "Alpha(Opacity=100)",
            backgroundColor: "black"
        });
    },
    modal: true
});

Frederic's answer was very close but it left me with one problem: I had more than one dialog on that page, and after I changed the overlay for the one dialog, it changed all of them until the page was reloaded. However, it did give me an idea;

First I stored the default values into variables (page scope), and then set my custom style.

var overlay = $(".ui-widget-overlay");
baseBackground = overlay.css("background");
baseOpacity = overlay.css("opacity");
overlay.css("background", "#000").css("opacity", "1");

Then when the dialog is closed, I restored those values.

$(".ui-widget-overlay").css("background", baseBackground).css("opacity", baseOpacity);

The main reason for storing them in variables (as opposed to resetting them to explicit values) is for maintainability. This way, even if the site.css changes, it will work.

Thanks for your help!

Change background:

$(".ui-widget-overlay").css({background: "#000", opacity: 0.9});

Restore background to CSS values:

$(".ui-widget-overlay").css({background: '', opacity: ''});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!