简体   繁体   中英

Resize IFRAME to Remove Scrollbars

I have an iframe on my page that I want resized every time the contents changes so that there are no scrollbars. The contents of the frame changes frequently without changing the URL. I want all of the content from the frame to show all the time, without having the screen flicker while the frame is resizing. The parent and frame are on the same domain.

Right now I call a function to set the frame size whenever I think the size has changed. How do I do this without calling this function everywhere?

If it helps, I am using angularJS.

You can get the iFrames content height by [iframe] .contentWindow.document.body.offsetHeight . If you don't know when the the content size changes you have to check it manually by using setInterval() .

尝试使用iframe-resizer ,一个用于自动调整iframe大小的嵌入式js模块。

Try this, call the re-size function in a event listener, when ever the iframe loads this will be triggered

var iframe = document.getElementById('myIframe');
    var resizeFunction= function() {$("#myIframe").css({
       height: iframe.$("body").outerHeight()
    });};
    if(iframe.addEventListener){
        iframe.addEventListener('load', resizeFunction, true);
    }else if(iframe.attachEvent){
        iframe.attachEvent('onload',resizeFunction);
    }

This is a function wich I used on one of my site. I modified the code to be put in a directive.

Note : In the iframe your container must have the ID ifrm_container

<iframe resize-iframe id="iframe" src="...">

.directive('resize-iframe', function() {
    return {
       restrict: 'A',
       link: function ( scope, elm, attrs ) {

        var container = elm.contentWindow.document.getElementById('ifrm_container'); // Iframe container. Usualy a div. 

        function autoResize(){
             ifrmNewHeight = container.offsetHeight; // New height of the document.

             if(ifrmNewHeight !== ifrmOldHeight) {
                ifrmOldHeight = ifrmNewHeight + 30; // +30 for no scrollbar.
                ifrm.style.height= (ifrmNewHeight + 30) + "px"; // Set iframe style.
             }

            setTimeout(autoResize, 250);
        }
      // First call of autoResize().
      autoResize();
  };
});

I have tested this solution on all browser even IE7 and it works well but not in a directive (changed some element).

THIS DIRECTIVE IS NOT TESTED

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