iframe 完全跨域自适应高度

本文介绍了一种实现跨域页面间通信的方法,并详细解释了如何让iframe自适应其内容高度,确保良好的用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、跨域访问页面,
需要访问后台的页面,通过后台调转
2、跨域自适应宽高

 

 
思路:通过相互嵌套,获取跨域页面的高度,通过src传回到本域,通过parent方法设置主页的iframe的高度
  • index.jsp 本域
var ifr_el = document.getElementById("content");
function getIfrData(data){
//console.log("index:"+data);
if(oldHeight!=data){
oldHeight=data;
ifr_el.style.height = data+"px";
}
}
  • B.jsp 跨域
<%@include file="/static/iot/proxybase.html"%>
<iframe id="iframe_proxy" src="http://192.16.199.10:8060/Puriew/static/iot/middle.html#0" width="0" style="display: none;"></iframe>
<script>
var oldHeight_proxy = 0,
ifr_el = document.getElementById("iframe_proxy");
t_proxy && clearInterval(t_proxy);
var t_proxy = setInterval(function(){
var height_proxy = $("#body_1").height();//获取body的高度,跨域情况下 document.body.scrollHeight;获取的是ifream设定之后的高度
//console.log("proxy: \t"+height_proxy+"\t oldHeight_proxy:"+oldHeight_proxy);
if(oldHeight_proxy != height_proxy) {
oldHeight_proxy = height_proxy;
ifr_el.src += '#' +height_proxy;
}
},200);
</script>
  • middle.jsp 本域
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var oldHeight_middle = 0;
t_middle && clearInterval(t_middle);
var t_middle = setInterval(function(){
var height_middle = location.href.split('#')[location.href.split('#').length-1];
if(height_middle && height_middle != oldHeight_middle) {
console.log("middle:"+oldHeight_middle)
oldHeight_middle = height_middle;
if(window.parent.parent.parent.getIfrData) {
window.parent.parent.parent.getIfrData(oldHeight_middle);// 传到index.jsp 本域
}
}
},200);
</script>
</body>
</html>
 
 
参考链接:
iframe之间通信问题及iframe自适应高度问题 http://www.cnblogs.com/tugenhua0707/p/3346522.html

转载于:https://www.cnblogs.com/litblank/p/8182613.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值