2012-01-14 130 views
6

我正在使用jQuery UI對話框來加載ajax內容。它正確地將對話框垂直放置,但是,使用width: "auto"選項時,它不會水平居中。它偏離中心,像中心右側100px。使用jQuery對話框自動調整寬度和高度

這裏是我的代碼:

$('.open').live('click', function(e) { 
    e.preventDefault(); 
    $("#modal").load($(this).attr('href')).dialog({ 
     title: $(this).attr('title'), 
     modal: true, 
     autoOpen: true, 
     draggable: false, 
     resizable: false, 
     width: 'auto', 
     position: ['center', 'top'] 
    }); 
}); 

任何想法,如果有辦法把它自動調整並保持居中?

編輯:這工作:

$("#modal").load($(this).attr('href'), function() { 
    $("#modal").dialog({ 
     title: $(this).attr('title'), 
     width: 'auto', 
     modal: true, 
     autoOpen: true, 
     draggable: false, 
     resizable: false, 
     position: ['center', 150], 
     create: function(event, ui) {} 
    }); 
}); 
+0

添加CS s'margin-left:auto; margin-right:auto;'把你的對象設置爲中心,這樣做。 – 2012-01-14 21:59:41

+0

jquery調整它,它會覆蓋任何默認樣式 – David 2012-01-14 22:03:18

+0

後創建它,我困了,我不能找到它,對不起:D,但是當你的對象插入你的頁面,你可以改變它的位置。 – 2012-01-14 22:18:23

回答

0

試試這個代碼。它適用於我,並且是跨瀏覽器。

$(window).resize(function(){ 
     $('.className').css({position:'absolute', left:($(window).width() 
     - $('.className').outerWidth())/2, 
     top: ($(window).height() 
     - $('.className').outerHeight())/2 
     }); 
}); 

// To initially run the function: 
$(window).resize(); 

從此創建對話框應該是非常簡單的。

2

爲避免定位問題,您應該在創建或打開對話框之前等待內容加載。否則:

  1. jQuery UI的對話框將計算
  2. 當加載內容時,對話框的右側延伸,而左側固定不變,以適應內容的寬度和中樞,引起出現轉移的對話框向右

示例代碼應該改成這樣:

$("#modal").load("/ajax/content.html", function() { 
    // callback is executed after post-processing and HTML insertion has been performed 
    // this refers to the element on which load method was called 
    $(this).dialog({ 
    modal: true, 
    autoOpen: true, 
    draggable: false, 
    resizable: false, 
    width: "auto", 
    position: { my: "top", at: "top", of: window } 
    }); 
}); 
相關問題