2012-05-15 17 views
0

我使用的是一个jQuery弹出窗口,只是想知道如何使框保持中心,当我改变我的浏览器窗口宽度,目前它获取页面加载中心点,并保持在当我改变宽度时该位置。页面大小变化时弹出中心框

这是我使用弹出功能代码:

//Popup dialog 
function popup(message) { 

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

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

// Set overlay to fill screen 
$("#dialog-overlay").css("width","100%").fadeIn(); 

// Set dialogue box 80px from top and central 
$('#dialog-box').css({top:80, left:dialogLeft}).fadeIn(); 

// display the message 
//$('#dialog-message').html(message); 

// Close button fades out overlay and message 
$('.button').live('click',function() 
{ 
    $(this).parent().fadeOut(); 
    $('#dialog-overlay').fadeOut(); 
    return false; 
}); 

} 

回答

2

一个JavaScript解决方案是使用window.onresize这也是引发每当有什么事情发生了窗口的大小。

window.onresize = function() { 
    var maskWidth = $(window).width(); 
    var dialogLeft = (maskWidth/2) - ($('#dialog-box').width())/2; 
    $('#dialog-box').css({top:80, left:dialogLeft}); 
} 

可能最好把内部代码放到一个函数中以保存重复它。

+0

完美地工作,正是我所追求的,非常感谢! – huddds

+0

没问题:)。 – Timm

0

除非您需要支持IE6,否则查看使用位置可能是有意义的:固定并执行CSS中的大部分工作而不是JS。

E.g.

#dialog-overlay { 
    position: fixed; 
    top: 0; 
    right: 0; 
    bottom: 0; 
    left: 0; 
} 

#dialog-box { 
    position: fixed; 
    top: 50%; 
    left: 50%; 
    width: 400px; 
    height: 500px; 
    margin: -250px 0 0 -200px; /* width and height divided by 2 */ 
} 

但是,这里假定您有一个固定的宽度/高度对话框。

+0

可悲的是,很多用户都在运行较旧的计算机,因此需要尽可能使用跨浏览器。但感谢您的答案 – huddds