遇到的问题:在帮别人做网页时,强调只能使用js,css,htm实现,在写的时后想实现点击导航栏跳转时只改变部分页面,就想到了使用iframe嵌套网页,但遇到一个问题,嵌套的网页不能实现高度自适应,使得内容只显示一部分,所有本文章就是用来解决这一问题的
提示:以下是部分代码,样式就不展示了
原理
通过js来获取iframe内部内容的高度,再把该值赋值给iframe标签,改变iframe标签的高度
index.html
<!--导航栏-->
<div id="nav">
<ul>
<li><a class="aLabel" href="#" onclick="toHome()">首页</a></li>
<li><a class="aLabel" href="#" onclick="toGeographic()">地理气候</a></li>
<li><a class="aLabel" href="#" onclick="toScenic()">旅游景点</a></li>
<li><a class="aLabel" href="#" onclick="toHistory()">历史沿革</a></li>
</ul>
</div>
<hr/>
<!--主体内容-->
<div id="hc">
<iframe id="iframe" src="./home.html" scrolling="no" onload="GetIframeStatus()"></iframe>
</div>
修改代码
index.js
var Timeout;
var iframe
/*页面加载完执行*/
window.onload = function () {
iframe = document.getElementById("iframe");
GetIframeStatus(iframe)
}
/*窗口改变时执行*/
window.onresize = function () {
GetIframeStatus(iframe)
}
// iframe高度自适应
function GetIframeStatus(iframe,Height) {
Timeout = setTimeout(function () {
if (!iframe) return;
iframe.height = (iframe.Document ? iframe.Document.body.scrollHeight : iframe.contentDocument.body.offsetHeight)
}, 200)
}
// 跳转到 “首页” 页面
function toHome() {
iframe.src = '../html/home.html'
GetIframeStatus(iframe)
}
// 跳转到 “地理气候” 页面
function toGeographic() {
iframe.src = '../html/geographic1.html'
GetIframeStatus(iframe)
}
// 跳转到 “旅游景点” 页面
function toScenic() {
iframe.src = '../html/scenic.html'
GetIframeStatus(iframe)
}
// 跳转到 “历史沿革” 页面
function toHistory(){
iframe.src = '../html/history.html'
GetIframeStatus(iframe)
}