tnblog
首页
视频
资源
登录
愿你出走半生,归来仍是少年
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

iframe自适应高度与配合net core使用

8938人阅读 2019/2/11 21:57 总访问:1628637 评论:0 收藏:0 手机
分类: 前端


去掉iframe边框

frameborder="0"


去掉滚动条

scrolling="no"


iframe 自适应高度

如果内容是固定的,那么就很简单,可以通过直接给它定义一个高度和被嵌套的高度一样就可以了

内容宽度变化的iframe高度自适应

<iframe src="backtop.html" frameborder="0" scrolling="no" id="test" onload="this.height=100"></iframe>
<script type="text/javascript">
function reinitIframe(){
var iframe = document.getElementById("test");
try{
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
console.log(height);
}catch (ex){}
}
window.setInterval("reinitIframe()", 200);
</script>


跨域下的iframe自适应高度

跨域的时候,由于js的同源策略,父页面内的js不能获取到iframe页面的高度。需要一个页面来做代理。

方法如下:假设www.a.com下的一个页面a.html要包含www.b.com下的一个页面c.html。

我们使用www.a.com下的另一个页面agent.html来做代理,通过它获取iframe页面的高度,并设定iframe元素的高度。


a.html中包含iframe:

<iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no" style="border:0px;"></iframe>

在c.html中加入如下代码:

<iframe id="c_iframe"  height="0" width="0"  src="http://www.a.com/agent.html" style="display:none" ></iframe>
<script type="text/javascript">
(function autoHeight(){
var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
var c_iframe = document.getElementById("c_iframe");
c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;  // 这里通过hash传递b.htm的宽高
})();
</script>

然后,agent.html中放入一段js:

<script type="text/javascript">
var b_iframe = window.parent.parent.document.getElementById("Iframe");
var hash_url = window.location.hash;
if(hash_url.indexOf("#")>=0){
var hash_width = hash_url.split("#")[1].split("|")[0]+"px";
var hash_height = hash_url.split("#")[1].split("|")[1]+"px";
b_iframe.style.width = hash_width;
b_iframe.style.height = hash_height;
}
</script>


画了一个简单粗糙的思路图:

但是在net core下去使用一直不行

经过查看在net core中iframe如果是跨域的根本就没有被加载,所以js这些根本没有去执行

连请求都没有去请求

找了很久原因应该是net core中默认使用的是htts:

然而:

HTTPS页面里动态的引入HTTP资源,比如引入一个js文件,会被直接block掉的.在HTTPS页面里通过AJAX的方式请求HTTP资源,也会被直接block掉的。 


然后发现了问题其实就不然解决了

在net core中使用http去访问就好了,net core中默认开启了一个https,一个http我们使用http那个端口去访问就好了

这里可以看到使用http的是5000端口


然后去访问就可以加载成功了!





参考:http://caibaojian.com/iframe-adjust-content-height.html




欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价