modal pop up window to fit within browser view if

2019-04-15 08:07发布

问题:

I've went to this tutorial to do a modal pop up window, and it seems pretty nice for what I need to do. However, I was wondering if someone can help me figure out what I need to calculate to change the dialog box so it'll follow whenever you resize the browser. This tutorial is good because if you resize the browser (width-wise), the box will follow and go into the middle. But if it is height-wise, it wont.

Tutorial : Here

I'm thinking it has to do with these codes :

    // get the screen height and width  
var maskHeight = $(document).height();  
var maskWidth = $(window).width();

// calculate the values for center alignment
var dialogTop =  (maskHeight/3) - ($('#dialog-box').height()/3);  
var dialogLeft = (maskWidth/2) - ($('#dialog-box').width()/2); 

// assign values to the overlay and dialog box
$('#dialog-overlay').css({height:maskHeight, width:maskWidth}).show();
$('#dialog-box').css({top:dialogTop, left:dialogLeft}).show();

I've tried to use $(window).height() but I don't think that works either. I tried to mimic the width styles because that one works, but it doesn't seem to work with height? Can someone help me with this?

Thank you!

回答1:

Try this

Working demo. You can resize the window and try it re positions the dialog box automatically into center.

$(function(){
    $(window).resize(function(){
    // get the screen height and width  
    var maskHeight = $(window).height();  
    var maskWidth = $(window).width();

    // calculate the values for center alignment
    var dialogTop =  (maskHeight  - $('#dialog-box').height())/2;  
    var dialogLeft = (maskWidth - $('#dialog-box').width())/2; 

    // assign values to the overlay and dialog box
    $('#dialog-overlay').css({ height:$(document).height(), width:$(document).width() }).show();
    $('#dialog-box').css({ top: dialogTop, left: dialogLeft, position:"fixed"}).show();
    }).resize();
});