在许多网站中,我们经常需要使用 iframe
来嵌入其他网站的内容,但是 iframe
的高度通常是固定的,如果嵌入的网页内容高度超过了 iframe
的高度,那么就会出现滚动条,影响用户体验。此外,当 iframe
加载较慢时,用户可能会感到不耐烦。因此,在这篇文章中,我们将介绍如何为 iframe
添加加载效果以及自适应高度的功能,提高用户体验。
添加加载效果
我们可以使用 CSS
的 animation
属性为 iframe
添加加载效果。下面是一个示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
height: 300px;
position: relative;
overflow-y: auto;
}
.loading-box {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 1;
background: rgba(0, 0, 0, .8);
}
.loading-box::after {
position: absolute;
content: '';
top: 50%;
left: 50%;
border: 10px solid #f3f3f3;
border-top: 10px solid #3498db;
border-radius: 50%;
width: 25px;
height: 25px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% {
transform: translate(-50%, -50%) rotate(0deg);
}
100% {
transform: translate(-50%, -50%) rotate(360deg);
}
}
</style>
</head>
<body>
<h1>iframe加加载效果</h1>
<div class="box">
<iframe src="./iframe.html" frameborder="0" width="100%" height="98%" class="iframe-loading" onload="iframeloadingFun()"></iframe>
<div class="loading-box"></div>
</div>
</body>
<script>
function iframeloadingFun() {
setTimeout(() => {
document.querySelector('.loading-box').style.display = "none"
}, 500)
}
</script>
</html>
在上面的代码中,我们使用了 loading-box的伪元素来创建了一个加载效果。还使用了 border
属性来创建了一个圆形边框,然后使用 animation
属性来定义了一个旋转的动画效果。接下来,我们在 iframe
上使用了 onload
事件,当 iframe
加载完成时隐藏了加载效果。
自适应高度
自适应高度跟加载效果其实大同小异的,需要注意的是获取高度方法会存在兼容性问题,具体看示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>iframe根据子元素高度自适应</h1>
<div>
<iframe src="./iframe.html" frameborder="0" width="100%" class="iframe-auto" onload="iframeAutoHeightFun()"></iframe>
</div>
</body>
<script>
// 根据内嵌的页面自适应子页面的高度
function iframeAutoHeightFun() {
let iframeAuto = document.querySelector('.iframe-auto')
// 兼容性写法 iframeAuto.contentWindow.document浏览器旧版本
let iframeAutoDoc = iframeAuto.contentDocument || iframeAuto.contentWindow.document;
// 获取内嵌页面的实际高度
let iframeAutoDocContentHeight = iframeAutoDoc.documentElement.scrollHeight || iframeAutoDoc.body.scrollHeight;
iframeAuto.style.height = `${iframeAutoDocContentHeight}px`
}
</script>
</html>