共计 1502 个字符,预计需要花费 4 分钟才能阅读完成。
以下是一个比较复杂的 示例,展示了如何加载外部页面、控制样式和与
中加载的文档进行通信:
DOCTYPE html>
html>
head>
style>
.iframe-container {
position: relative;
width: 100%;
height: 500px;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
color: #fff;
font-size: 24px;
}
style>
head>
body>
div class="iframe-container">
iframe src="https://www.example.com" frameborder="0" width="100%" height="100%">iframe>
div class="overlay">Loading...div>
div>
script>
const iframeRef = document.querySelector('iframe');
const overlay = document.querySelector('.overlay');
iframeRef.addEventListener('load', function() {
overlay.style.display = 'none';
});
function sendMessageToIframe() {
const message = 'Hello from parent window!';
iframeRef.contentWindow.postMessage(message, '*');
}
window.addEventListener('message', function(event) {
if (event.source === iframeRef.contentWindow) {
const receivedMessage = event.data;
console.log('Received message from iframeRef:', receivedMessage);
}
});
script>
body>
html>
在上述示例中,我们创建了一个包含 的容器,通过 CSS 控制容器的样式和尺寸。同时,我们添加了一个覆盖层(
overlay
),用于在 加载期间显示加载信息。
在上面的代码片段中,
iframeRef
是父窗口(当前窗口)中的一个引用,通过iframeRef.contentWindow
可以访问到子窗口的window
对象。因此,postMessage 的作用是 父窗口向子窗口发送了一条消息。
在这种情况下,父窗口是通过 元素嵌入子窗口的,可以通过
iframeRef
元素的 contentWindow
属性来访问子窗口的 window
对象,并与子窗口进行通信。
在 JavaScript 部分,我们使用事件监听器和 postMessage()
方法实现了与 中加载的文档的通信。具体来说:
-
通过监听
的
load
事件,当页面加载完成时,隐藏覆盖层,显示中加载的内容。
-
在父窗口中定义了一个名为
sendMessageToIframe()
的函数,用于向发送消息。
-
在父窗口中监听
message
事件,当接收到来自的消息时,打印消息内容。
需要注意的是,由于跨域安全策略的限制,父窗口只能与同源的 进行通信。此示例中的通信是在同一个域名下进行的,因此没有出现跨域问题。
原文地址: 前端 html 中 iframe 的基本使用
正文完