效果图:
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