Resizing jQuery dialog div on iFrame content heigh

2019-09-19 15:18发布

问题:

I've a jquery dialog div. The div contains an iFrame to another ASP.Net page on the same domain. The iframe source page also contains jquery accordion control. Whenever the dialog is opened and accordion are expanded/collapsed, I need to resize the dialog box. Currently the contents are getting chopped off. Please note again that the dialog wraps the accordion within an iframe. I'm breaking my head against the wall to make things work. If somebody have a solution to this, then please help me out. Note: Everything is in same domain.

SOLVED See my ANSWER below.

回答1:

You need to get the child iframe to talk to the parent window when the accordion is toggled.

$yourAccordion.on('open', function(e){
  if(window.top && window.top.resizeDialog)
     window.top.resizeDialog($(window).width(),$(window).height());
});

Then in your parent page, have a global function called resizeDialog

window.resizeDialog = function(w,h){
  $('#dialog').find('iframe').attr({
    width: w,
    height: h
  });
};

Note: You'll most likely need to account for animation timing etc. You could also include this in the step function of the jQuery animate method you use to open/close the accordion to make it a bit smoother.



回答2:

The solution is for Same Origin (i.e. same domain). If you have access to iframe source page, put the following inline function globally:

    var iFrameIdOnParentSelector = "#Replace_with_iframe_id_on_parent";
    var iFrameContentSelector = "#Replace_with_content_id_on_iframe_src_page";
    function fireiFrameResize(iFrameIdOnParentSelector, iFrameContentSelector) {
     var frame = $(iFrameIdOnParentSelector, window.parent.document);
     var height = jQuery(iFrameContentSelector).height();
     var width = jQuery(iFrameContentSelector).width();
     frame.height(height);
     frame.width(width);
    }

In your accordion call, add activate property. Trigger the fireiFrameResize() method with it. The function will run on every expand and collapse of accordion.

     $("#accordionDiv").accordion({
      collapsible: true,
      active: false,
      heightStyle: "content",
      activate: function (event, ui) {
        fireiFrameResize(iFrameIdOnParentSelector, iFrameContentSelector);
      }
     });

On your calling page/control, where iFrame control is there, set it's height and width to some initial default. Do not set the dialog height and width containing the iframe. It'll take the iframe height and width by default. Please note the following:

  • My iframe is a server control inside a custom user control.
  • Since, iframe is a server control here, so I set ClientIdMode="Static". This avoids runtime id creation by ASP.Net engine.

Cheers. :)