iframe子页面与父页面元素的访问以及js变量的访问
参考链接:https://www.cnblogs.com/Capricorn-HCL/articles/4216302.html / https://zhidao.baidu.com/question/1759940378751684988.html
- iframe里子页面访问父页面元素
parent.document.getElementById('barch-approval-iframe');
- 父页面访问子页面元素
(1) document.getElementById('iframeId').contentDocument.getElementsByTagName('table'); //contentDocument后可以使用document相关方法 var tet = document.getElementById('iframeId').contentWindow.document.getElementById("text_inputId"); console.log(tet.value); (2) var iframe = document.getElementById("moving-iframe"); var body = iframe.contentWindow.document.body; //获取iframe body var form = $(body).find('form'); //获取iframe form元素 //拿取所有name对应的值 var inputTag = form.find("input[name]:not([type='radio'],[type='checkbox'])")
- 子页面访问父页面js变量
//父页面的js变量需为全局变量 var childObj= parent.parentObj //parentObj为父页面定义的变量 //childObj为子页面变量
- 子页面访问父页面方法
window.parent.paramMethod();
- 父页面访问子页面方法
var iframe = document.getElementById("moving-iframe"); iframe.contentWindow.Validate() //Validate为iframe里定义的方法
案例
-
以弹窗形式加载iframe,当iframe里元素增加时会导致iframe高度不够遮挡了下方的元素
如图:当附件个数不断增加时,保存提交的按钮会因iframe高度不够而挡住;
解决办法:当增加附件时手动去改变iframe高度(原有高度+最后一个附件的高度)var iframeObj = parent.document.getElementById('barch-approval-iframe'); //获取到本iframe iframeObj.height = parseInt(iframeObj.height)+$("#barch-approval-fileList li:last-child").height();
-
iframe高度根据内容自适应
<iframe :src="barchApprovalUrl" id="barch-approval-iframe" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no" style="width:100%;overflow-x:hidden;" v-on:load="getThisObject2()"> //重要 </iframe>
window.iframeObj2 = {}; //建议全局变量 function getThisObject(t) { window.iframeObj = t; }; //获取高度 function setIframeHeight2(iframe) { setTimeout(function() { if (iframe) { var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow; console.log(iframe.contentDocument.body.scrollHeight) if (iframeWin.document.body) { iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight; } } }, 200) }; getThisObject2: function() { //vue中定义方法 window.iframeObj2 = document.getElementById("barch-approval-iframe"); setIframeHeight2(iframeObj2); }