1. 程式人生 > >div裡巢狀iframe,設定iframe及div的高度自適應

div裡巢狀iframe,設定iframe及div的高度自適應

1. div+iframe

<div class="main">
	<iframe id="contentFrame" name="contentFrame" src="url" onload="javascript:reinitIframe('contentFrame',100);" style="width: 100%;" frameborder="0" scrolling="no"></iframe> 
</div>

2. js

<script>
	var browserVersion = window.navigator.userAgent.toUpperCase();  //使用navigator.userAgent判斷瀏覽器型別
	var isOpera = browserVersion.indexOf("OPERA") > -1 ? true : false;
	var isFireFox = browserVersion.indexOf("FIREFOX") > -1 ? true : false;
	var isChrome = browserVersion.indexOf("CHROME") > -1 ? true : false;
	var isSafari = browserVersion.indexOf("SAFARI") > -1 ? true : false;
	var isIE = (!!window.ActiveXObject || "ActiveXObject" in window);
	var isIE9More = (!-[1,] == false);  //其中 !-[1,] 在ie[6-8]中值為true
	function reinitIframe(iframeId, minHeight) {
	    try {
	        var iframe = document.getElementById(iframeId);
	        var bHeight = 0;
	        if (isChrome == false && isSafari == false) {
	            try {
	                bHeight = iframe.contentWindow.document.body.scrollHeight;
	            } catch (ex) {}
	        }
	        var dHeight = 0;
	        if (isFireFox == true){  //FireFox
	        	iframe.style.height = minHeight;
	            dHeight = iframe.contentWindow.document.documentElement.offsetHeight + 2;
	        }else if (isIE == false && isOpera == false && iframe.contentWindow) {  //Chrome、Safari
	            try {
	            	iframe.style.height = minHeight;
	            	dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
	            } catch (ex) {}
	        }else if (isIE == true && isIE9More) {//ie9+
	            var heightDeviation = bHeight - eval("window.IE9MoreRealHeight" + iframeId);
	            if (heightDeviation == 0) {
	                bHeight += 3;
	            } else if (heightDeviation != 3) {
	                eval("window.IE9MoreRealHeight" + iframeId + "=" + bHeight);
	                bHeight += 3;
	            }
	        }else {//ie[6-8]、OPERA
	            bHeight += 3;
	        }

	        var height = Math.max(bHeight, dHeight);
	        if (height < minHeight) height = minHeight;
	        iframe.style.height = height + "px";
	    } catch (ex) {}
	}
</script>