Adjust width and height of iframe to fit with content in it

前端 未结 30 2325
旧时难觅i
旧时难觅i 2020-11-22 02:09

I need a solution for auto-adjusting the width and height of an iframe to barely fit its content. The point is that t

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 02:30

    function resizeIFrameToFitContent(frame) {
    if (frame == null) {
        return true;
    }
    
    var docEl = null;
    var isFirefox = navigator.userAgent.search("Firefox") >= 0;
    
    if (isFirefox && frame.contentDocument != null) {
        docEl = frame.contentDocument.documentElement;
    } else if (frame.contentWindow != null) {
        docEl = frame.contentWindow.document.body;
    }
    
    if (docEl == null) {
        return;
    }
    
    var maxWidth = docEl.scrollWidth;
    var maxHeight = (isFirefox ? (docEl.offsetHeight + 15) : (docEl.scrollHeight + 45));
    
    frame.width = maxWidth;
    frame.height = maxHeight;
    frame.style.width = frame.width + "px";
    frame.style.height = frame.height + "px";
    if (maxHeight > 20) {
        frame.height = maxHeight;
        frame.style.height = frame.height + "px";
    } else {
        frame.style.height = "100%";
    }
    
    if (maxWidth > 0) {
        frame.width = maxWidth;
        frame.style.width = frame.width + "px";
    } else {
        frame.style.width = "100%";
    }
    }
    

    ifram style:

    .myIFrameStyle {
       float: left;
       clear: both;
       width: 100%;
       height: 200px;
       padding: 5px;
       margin: 0px;
       border: 1px solid gray;
       overflow: hidden;
    }
    

    iframe tag:

    
    

    Script tag:

    
    

提交回复
热议问题