jQuery模式窗口在内容为“”时不居中;注入“;在飞行中

jQuery Modal Window not centering when content is "injected" on the fly

本文关键字:窗口 模式 注入 飞行 jQuery      更新时间:2023-09-26

我对一个特定的脚本有一些问题。我发现了一个简单的模式窗口脚本,我正在尝试实现它。最初的功能是简单地隐藏/显示带有"静态"内容的窗口div。这很好,但我需要能够即时指定内容的能力。因此,我通过允许使用.load()函数来"注入"div的内容,然后脚本将正常显示窗口,从而改变了情况。然而,当模态关闭时,我使用.empty()清空了div的内容,以允许根据用于打开模型窗口的链接中的属性值动态添加不同的内容。

如果我使用.load()函数,而不是将<embed>代码硬编码到div的内容中,那么除了窗口不在屏幕中间之外,一切都很好。如果我硬编码<embed>对象,它的中心就很好,看起来很棒。

显然,如果<embed>对象被动态地注入div,那么整个窗口的高度/宽度会有差异。我尝试在脚本查找窗口div的总宽度/高度之前和之后定位.load()函数,但这似乎不会影响任何事情。

任何帮助都将不胜感激!!

这是脚本:

$(document).ready(function() {  
    //select all the a tag with name equal to modal
    $('a[name=modal]').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();
        //Get the A tag
        var id = $(this).attr('href');
        //Get source file for AJAX request
        var source = $(this).attr('src');
        //If source is set, send ajax request, and then load content into window
        if(source != undefined) {
            $('.window').load(source);
        }
        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        //Set heigth and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});
        //transition effect     
        $('#mask').fadeIn(1000);    
        $('#mask').fadeTo("slow",0.8);  
        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();
        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);
        //transition effect
        $(id).fadeIn(2000); 
    });
    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();
        $('#mask').fadeOut("slow");
        $('.window').fadeOut("slow", function() {       
            $(this).empty();
        });
    });     
    //if mask is clicked
    $('#mask').click(function () {
        $(this).fadeOut("slow");
        $('.window').fadeOut("slow", function() {
            $(this).empty();
        });
    });         
});

这是因为加载正在触发AJAX请求,并且在加载内容之前正在运行居中代码。您需要做的是将模态集中在ajax完整处理程序中。

$('.window').load(source,null,function(){ functionThatCentersModal() });