简体   繁体   中英

Dynamically adjust iFrame height of dynamically changing content height (explanation inside)

I have an iframe that consists of a form with some jQuery validation that causes the height of the content to increase if there are errors.

Below you can find the plugin that I use to dynamically change the height of my iFrame:

function doIframe(){
o = document.getElementsByTagName('iframe');
for(i=0;i<o.length;i++){
    if (/\bautoHeight\b/.test(o[i].className)){
        setHeight(o[i]);
        addEvent(o[i],'load', doIframe);
    }
  }
}

function setHeight(e){
if(e.contentDocument){
    e.height = e.contentDocument.body.offsetHeight + 35;
  } else {
    e.height = e.contentWindow.document.body.scrollHeight;
  }
}

function addEvent(obj, evType, fn){
  if(obj.addEventListener)
  {
   obj.addEventListener(evType, fn,false);
   return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
      return false;
  }
}

if (document.getElementById && document.createTextNode){
  addEvent(window,'load', doIframe);    
}

And to set the height I do $("#booking_iframe").iframeAutoHeight({minHeight: 840}); .


How do I modify the code (or perhaps use another code) to dynamically change the height of my iFrame if the height of the iFrame's content is changing because of the jQuery validation?

You can see this in action by going here and filling in the form in the sidebar.

To Change Hight if iFrame content changed its done here by jquery-resize-plugin:

Example & Code of using jQuery resize event :

Section [ Resizing an Iframe as its content grows ]

http://benalman.com/code/projects/jquery-resize/examples/resize/

Plugin Project URL:

http://benalman.com/projects/jquery-resize-plugin/

If you defined a function called something like resizeCallBackFunction() that resizes the iframe in the top level document (the one containing the iframe), then from the document in the iframe you can then call it (and pass an argument, like height) like this, whenever content in the the document in the iframe changes:

 window.top.window.resizeCallBackFunction(height);

This works reliably in all browsers (MSIE 6-9, Firefox, Chrome, Safari...).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM