1. 程式人生 > >iframe高度自動隨著子頁面的高度變化而變化(不止要在iframe標籤里加上this.height=this.contentWindow.document.body.scrollHeight)

iframe高度自動隨著子頁面的高度變化而變化(不止要在iframe標籤里加上this.height=this.contentWindow.document.body.scrollHeight)

最近使用iframe整合頁面遇到一些難題,走了很多彎路才解決,藉此記錄一下;

 1  <!-- 頁面主體內容 -->
 2     <div class="iframe-wrapper" >
 3         <iframe scrolling="no" id="iframe1" name="iframe1"
 4                 src="../index/index_copy.html" frameborder="0" width="100%" height="1000"></iframe>
 5     </div>
 6  <!-- 下面的程式碼也可以在iframe標籤內寫成 onload="this.height=this.contentWindow.document.body.scrollHeight" -->
 7 <script>
 8     $('#iframe1').load(function (){
 9         this.height=this.contentWindow.document.body.scrollHeight;
10     })
11 </script>

以上寫完之後,iframe的高度就可以隨著內嵌的子頁面變化而變化,但是問題也出現了,子頁面body的高度並不完全等於iframe的高度,

這樣就會導致顯示的頁面很醜,有的也會顯示不全;網上試了很多辦法都沒成功,最後找到一種方法,該方法的原理就是監聽元素的變化,

一旦元素一變化就把子頁面的高度設定到iframe的高度中,廢話不說了,上程式碼;

<!-- 將以下程式碼放到頁面呼叫的公共js中/也可以單獨在需要的頁面引入 -->
function bodyResize(){
    parent.window.document.getElementById('iframe1').height=(document.body.scrollHeight);
}

/**
 * 動態調整iframe高度的公共方法
 */
var EleResize = {
    _handleResize: function (e) {
        var ele = e.target || e.srcElement;
        var trigger = ele.__resizeTrigger__;
        if (trigger) {
            var handlers = trigger.__z_resizeListeners;
            if (handlers) {
                var size = handlers.length;
                for (var i = 0; i < size; i++) {
                    var h = handlers[i];
                    var handler = h.handler;
                    var context = h.context;
                    handler.apply(context, [e]);
                }
            }
        }
    },
    _removeHandler: function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (handlers) {
            var size = handlers.length;
            for (var i = 0; i < size; i++) {
                var h = handlers[i];
                if (h.handler === handler && h.context === context) {
                    handlers.splice(i, 1);
                    return;
                }
            }
        }
    },
    _createResizeTrigger: function (ele) {
        var obj = document.createElement('object');
        obj.setAttribute('style',
            'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden;opacity: 0; pointer-events: none; z-index: -1;');
        obj.onload = EleResize._handleObjectLoad;
        obj.type = 'text/html';
        ele.appendChild(obj);
        obj.data = 'about:blank';
        return obj;
    },
    _handleObjectLoad: function (evt) {
        this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__;
        this.contentDocument.defaultView.addEventListener('resize', EleResize._handleResize);
    }
};
if (document.attachEvent) {//ie9-10
    EleResize.on = function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (!handlers) {
            handlers = [];
            ele.__z_resizeListeners = handlers;
            ele.__resizeTrigger__ = ele;
            ele.attachEvent('onresize', EleResize._handleResize);
        }
        handlers.push({
            handler: handler,
            context: context
        });
    };
    EleResize.off = function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (handlers) {
            EleResize._removeHandler(ele, handler, context);
            if (handlers.length === 0) {
                ele.detachEvent('onresize', EleResize._handleResize);
                delete  ele.__z_resizeListeners;
            }
        }
    }
} else {
    EleResize.on = function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (!handlers) {
            handlers = [];
            ele.__z_resizeListeners = handlers;

            if (getComputedStyle(ele, null).position === 'static') {
                ele.style.position = 'relative';
            }
            var obj = EleResize._createResizeTrigger(ele);
            ele.__resizeTrigger__ = obj;
            obj.__resizeElement__ = ele;
        }
        handlers.push({
            handler: handler,
            context: context
        });
    };
    EleResize.off = function (ele, handler, context) {
        var handlers = ele.__z_resizeListeners;
        if (handlers) {
            EleResize._removeHandler(ele, handler, context);
            if (handlers.length === 0) {
                var trigger = ele.__resizeTrigger__;
                if (trigger) {
                    trigger.contentDocument.defaultView.removeEventListener('resize', EleResize._handleResize);
                    ele.removeChild(trigger);
                    delete ele.__resizeTrigger__;
                }
                delete  ele.__z_resizeListeners;
            }
        }
    }
}

最後子頁面的js的初始化的前面呼叫

 1 //動態調整iframe高度
 2 EleResize.on(document.body,function(){bodyResize();});
 3 
 4 //頁面初始化程式碼
 5 $(function () {
 6     //獲取列表資料
 7     getData(nowPage);
 8     // $("body").live("resize",bodyResize());
 9     //$("body").resize(bodyResize());
10     // $("body").resize(alert(123455));
11 });

這樣iframe頁面就可以自動隨著子頁面的標籤變化而動態變化了

&n