Im trying to write a quick plugin that will load some AJAX content into a jQuery UI dialog and resize and center the dialog accordingly. Here's the gist of what it does:
$(mySelector).html('Loading...').load(options.url, function() {
element = $(mySelector);
element.dialog('option', 'height', element.height() + 50);
element.dialog('option', 'width', element.width());
element.dialog('option', 'position', 'center');
});
The height seems to be OK (adding some for padding the dialog adds) but the width is ALWAYS 274 no matter what. I think the dialog itself is setting the size limits on it. How can I set it to what the natural width of the loaded content would be?
Edit/Addition: It is returning the default size of the modal. Bec开发者_StackOverflow中文版ause even if it contains content that is wider (say a 500px image), the parent container (mySelector) may not be that wide (in FF at least), so it was always the default (300 - padding = 274). Is there any way to auto-detect what the width of the returned content would be at a minimum without it scrolling?)
I used to have the same problem. If I remember, you need to first load the dialog and then load the content in it. That way, the dialog will auto resize to its content (with width=auto).
More less like this (tested):
var $dialog; //Must be at the global scope
function dialog(url) {
$dialog.dialog("option", "width", "auto");
$dialog.dialog("option", "height", "auto");
$.get(url,{},function(html) {
$dialog.html(html);
$dialog.dialog("open");
});
}
$(function() {
//Initialize (without showing it)
var $dialog = $('<div id="dialog" title=""></div>').dialog({
autoOpen: false,
modal: true
});
});
Then you can do this:
dialog(someURL);
They key was to call open again after the content has been loaded, then re-center it. This will cause the dialog to do it's magic and resize everything properly and re-center itself. I'll post a plugin here once I get it cleaned up.
A little late, but this is my working solution:
$("#dialog" ).dialog({
autoOpen: false,
modal: true,
width: 'auto',
height: 'auto',
create: function(){
var content = '<h1>This is some Content</h1>';
$('.content', this).replaceWith(content);
buttons: {
Ok: function(){
$(this).dialog("close");
}
}
});
The trick was to insert the dialog content in the 'create' handler.
精彩评论