iframe父子頁面互相調取方法元素
阿新 • • 發佈:2020-08-04
父頁面
// parent.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Parent</title> <style> body, html { padding: 0; margin: 0; } .header-wrap { width: 100%; height: 40px; line-height: 40px; padding: 0 20px; background-color: darkcyan; color: #ffffff; margin: 0; display: flex; align-items: center; justify-content: space-between; font-size: 16px; box-sizing: border-box; } .header-btn { font-size: 12px; cursor: pointer; } #subPage { padding: 0; margin: 0; width: 100%; height: calc(100vh - 40px); background-color: #f9f9f9; } </style> </head> <body> <div class="header-wrap"> <span>父頁面標題</span> <span class="header-btn" onclick="getChildrenFun()">儲存</span> </div> <iframe id="subPage" src="./children.html" frameborder="0"></iframe> <script> function isParent() { console.log('這裡是父頁面') } function getChildrenFun() { console.log('調子頁面方法') const subPageFun = document.querySelector('#subPage').contentWindow // 調方法 subPageFun.isChildren() // 取樣式 const subPageDoc = document.querySelector('#subPage').contentDocument console.log('子頁面樣式獲取--子頁面高度', subPageDoc.body.clientHeight) console.log('子頁面樣式獲取--子頁面指定元素高度', subPageDoc.querySelector('.abc-box').clientHeight) } </script> </body> </html>
子頁面
// children.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Children</title> <style> body, html { padding: 0; margin: 0; } .sub-page-wrap { margin: 0; padding: 20px; box-sizing: border-box; } .abc-box { width: 100px; height: 100px; background-color: #eee; margin-top: 20px; padding: 20px; box-sizing: border-box; } </style> </head> <body> <div class="sub-page-wrap"> <div>子頁面內容</div> <button onclick="getParentFun()" style="margin-top: 20px;">呼叫父頁面方法</button> <div class="abc-box">abc</div> </div> <script> function isChildren() { console.log('這裡是子頁面') } function getParentFun() { console.log('調父頁面方法') var mainPageFun = parent // 調方法 mainPageFun.isParent() // 調樣式 var mainPageDoc = window.parent.document console.log('父頁面樣式獲取--父頁面高度', mainPageDoc.body.clientHeight) console.log('父頁面樣式獲取--父頁面指定元素高度', mainPageDoc.querySelector('.header-wrap').clientHeight) } </script> </body> </html>