iframe框架

定义

iframe 元素会建立包含另一个文档的内联框架(即行内框架)。html

属性

属性 描述
align
  • left
  • right
  • top
  • middle
  • bottom

不同意使用。请使用样式代替。跨域

规定如何根据周围的元素来对齐此框架。框架

frameborder
  • 1
  • 0
规定是否显示框架周围的边框。
height
  • pixels
  • %
规定 iframe 的高度。
width
  • pixels
  • %
规定 iframe 的宽度度。
longdesc URL 规定一个页面,该页面包含了有关 iframe 的较长描述。
marginheight   pixels 定义 iframe 的顶部和底部的边距。
marginwidth pixels 定义 iframe 的左侧和右侧的边距。
name frame_name   规定 iframe 的名称。
sandbox
  • ""
  • allow-forms
  • allow-same-origin
  • allow-scripts
  • allow-top-navigation
启用一系列对 <iframe> 中内容的额外限制。
scrolling
  • yes
  • no
  • auto
规定是否在 iframe 中显示滚动条。
seamless seamless 规定 <iframe> 看上去像是包含文档的一部分。
src URL 规定在 iframe 中显示的文档的 URL。
srcdoc HTML_code 规定在 <iframe> 中显示的页面的 HTML 内容。

传值

postMessage

postMessage方法容许来自不一样源的脚本采用异步方式进行有限的通讯,能够实现跨文本档、多窗口、跨域消息传递。less

语法: otherWindow.postMessage(message, targetOrigin, [transfer]); 异步

  • otherWindow:其余窗口的引用,如iframe的contentWindow、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
  • message:将要发送到其余window的数据。
  • targetOrigin:指定那些窗口能接收到消息事件,其值能够是字符串“*”表示无限制,或者是一个URL。
  • transfer:是一串和message同时传递的Transferable对象,这些对象的全部权将被转移给消息的接收方,而发送方将再也不保留全部权。

postMessage方法被调用时,会在全部页面脚本执行完毕以后像目标窗口派发一个MessageEvent消息,该MessageEvent消息有四个属性:post

  • type:表示该message的类型
  • data:为postMessage的第一个参数
  • origin:表示调用postMessage方法窗口的源
  • source:记录调用postMessage方法的窗口对象

 例子

父页面:spa

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>主页面</h1>
<iframe id="child" src="http://localhost:63342/test/b.html"></iframe>
<div>
    <h2>主页面接收消息区域</h2>
    <span id="message"></span>
</div>
</body>
<script>
    window.onload = function(){
        document.getElementById('child').contentWindow.postMessage("主页面消息", "*")
    }
    window.addEventListener('message', function(event){
        document.getElementById('message').innerHTML = "收到" + event.origin + "消息:" + event.data;
    }, false);
</script>
</html>

子页面:code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h2>子页面</h2>
<div>
    <h3>接收消息区域</h3>
    <span id="message"></span>
</div>
</body>
<script>
    window.addEventListener('message',function(event){
        if(window.parent !== event.source){return}
        console.log(event);
        document.getElementById('message').innerHTML = "收到" + event.origin + "消息:" + event.data;
        top.postMessage("子页面消息收到", '*')
    }, false);
</script>
</html>
相关文章
相关标签/搜索