效果圖:
index.html (主頁面)
<!DOCTYPE HTML>
<style>
body {
margin: 0;
padding: 0;
}
.iframe-box{
box-sizing: border-box;
padding: 0 10px;
}
#my-frame{
border: 1px solid red !important;
}
.footer {
margin-top: 15px;
padding: 0 10px;
text-align: center;
}
.btn-sign{
min-width: 80px;
}
.desc-text {
color: darkgray;
font-size: 12px;
margin: 10px auto;
}
</style>
<script>
//window.onload = function () {
//}
</script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" />
<script src="index.js"></script>
<title></title>
</head>
<body>
<!--方案一:用setTimeout (不推薦:用延時處理,有卡頓感覺) -->
<!--<iframe id="my-frame" src="a.html" frameborder="0" scrolling="no" style="border:0px; width:100%;"></iframe>-->
<!--方案二:用onload (推薦:效果平滑) -->
<div class="iframe-box" >
<iframe id="my-frame" src="a.html" frameborder="0" scrolling="no" style="border:0px; width: 100%" onLoad="setIframeHeight(this.id)"></iframe>
</div>
<div class="footer">
<button class="btn-sign">簽到</button>
<div class="desc-text">每次簽到積1分</div>
</div>
</body>
</html>
a.html (被嵌入頁面)
<img src="a1.jpeg" style="width:100%" />
<P style='font-size: 18px;'>
你好嗎!
</P>
<div>
<span style='font-size: 12px; color: orange;'>你猜猜!</span>
<span style="font-size:1.8rem; color: red; font-weight: 800; margin-left: 10px;">錯了!</span>>
</div>
index.js (提供2種計iframe高度的方法)
////方案一:
////自適應 iframe 內容高度
//function setIframeHeight() {
// var iframe = document.getElementById("my-frame");
// try {
// var userAgent = window.navigator.userAgent; //取得瀏覽器的userAgent字符串
// if (userAgent.indexOf("Chrome") > -1) {
// //documentElement 不能替換成body 否則 google瀏覽器不兼容
// var bHeight = iframe.contentWindow.document.documentElement.scrollHeight;
// } else {
// //documentElement 不能替換成body 否則 google瀏覽器不兼容
// var bHeight = iframe.contentWindow.document.body.scrollHeight;
// }
// iframe.height = bHeight;
// } catch (ex) {
// }
//}
//window.onload = function () {
// window.setTimeout("setIframeHeight()", 200);
//}
//方案二:用onload
function getDocHeight(doc) {
doc = doc || document;
var body = doc.body;
var html = doc.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
return height;
}
function setIframeHeight(id) {
var ifrm = document.getElementById(id);
var doc = ifrm.contentDocument ? ifrm.contentDocument : ifrm.contentWindow.document;
ifrm.style.visibility = 'hidden';
ifrm.style.height = "10px"; // reset to minimal height ...
ifrm.style.height = getDocHeight(doc) + 4 + "px";
ifrm.style.visibility = 'visible';
}
【注意點】
1、禁止網頁縮放; (設 meta name="viewport" ...)
2、計算iframe的高度; (選js中其種一種方案)
3、處理iframe的寬度;(設iframe寬度)
4、圖片寬度的處理; (設a.html內圖片寬度)
5、如果出現亂碼,將html文件以UTF-8格式存儲;
6、強調:必須要在發佈後才能看到效果!必須要在發佈後才能看到效果!必須要在發佈後才能看到效果!
參考資料:
《iframe自適應高度》https://cloud.tencent.com/developer/article/1410326
附圖片:a1.jpeg