2012-01-14 135 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 } 
    }); 
}); 
相关问题