頁面1 localhost:8086/index.html複製代碼javascript
<div style="width:200px; float:left; margin-right:200px;border:solid 1px #333;">
<div id="color">Frame Color</div>
</div>
<div>
<iframe id="child" src="http://localhost:8087/index.html"></iframe>
</div>
<script type="text/javascript">
window.οnlοad=function(){
window.frames[0].postMessage('getcolor','http://localhost:8087');
}
window.addEventListener('message',function(e){
var color=e.data;
document.getElementById('color').style.backgroundColor=color;
},false);
</script>html
頁面2 localhost:8087/index.htmljava
<body style="height:100%;">
<div id="container" οnclick="changeColor();" style="widht:100%; height:100%; background-color:rgb(204, 102, 0);">
click to change color
</div>
<script type="text/javascript">
var container=document.getElementById('container');
window.addEventListener('message',function(e){
if(e.source!=window.parent) return;
var color=container.style.backgroundColor;
window.parent.postMessage(color,'*');
},false);
function changeColor () {
var color=container.style.backgroundColor;
if(color=='rgb(204, 102, 0)'){
color='rgb(204, 204, 0)';
}else{
color='rgb(204,102,0)';
}
container.style.backgroundColor=color;
window.parent.postMessage(color,'*');
}
</script>
</body>瀏覽器
在瀏覽器瀏覽 localhost:8086/index.html 點擊iframe頁面能夠改變父類的顏色post
就是這麼easyhtm