<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>我是PC的</title> <style> .iframme-wrapper { width: 400px; height: 150px; background: pink; margin: 50px auto; position: relative; } .mask { position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 2; } .sonBtn-wrapper { width: 300px; margin: 0 auto; display: flex; justify-content: space-around; } #sonBtn1, #sonBtn2 { width: 120px; height: 100px; background: #000; color: #fff; } #showPage { font-size: 30px; text-align: center; margin: 50px 0; } </style> </head> <body> <div class="iframme-wrapper"> <div class="mask"></div> <iframe src="http://127.0.0.1:5500/mPage.html" width="400" height="150" id="iframeDom" frameborder="0" ></iframe> </div> <div class="sonBtn-wrapper"> <button id="sonBtn1">变文字</button> <button id="sonBtn2">变颜色</button> </div> <div id="showPage"></div> </body> <script> window.onload = function () { let iframeDom = document.getElementById('iframeDom').contentWindow let btndom1 = document.getElementById('sonBtn1') let btndom2 = document.getElementById('sonBtn2') let pageUrl = 'http://127.0.0.1:5500/mPage.html' btndom1.onclick = function () { iframeDom.postMessage({ type: 'changeTest' }, pageUrl) } btndom2.onclick = function () { iframeDom.postMessage({ type: 'changeColor' }, pageUrl) } let showPage = document.getElementById('showPage') window.addEventListener('message', function (event) { let content = event.data.content showPage.innerHTML = '我接受了页面通信内容为' + content }) } </script> </html>
|