2012-05-15 23 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