iframe嵌入页面自适应目标页面的高度

前端之家收集整理的这篇文章主要介绍了iframe嵌入页面自适应目标页面的高度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。编程之家小编现在分享给大家,也给大家做个参考。

iframe 嵌入页面自适应目标页面的高度,要把页面放到本地,不然会报错,并且实现不了自适应高度的功能,报错:Blocked a frame with origin "null" from accessing a cross-origin frame;原因:跨页面操作涉及域的概念(origin),错误的意思是:未捕获的安全错误:阻止了一个域为 null 的 frame 页面访问另一个域为 null 的页面代码运行时在本地直接用浏览器打开的,地址栏是 file:///的页面,只需改为 localhost 访问就行。

第一种:

在引入 iframe 的页面加上

function setIframeHeight(iframe) {

if (iframe) {

var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;

if (iframeWin.document.body) {

iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;

}

}

};

 

window.onload = function () {

setIframeHeight(document.getElementById('iframe'));

};

第二种:

在引入 iframe 的页面加上

$("#iframe").load(function(){

var mainheight = $(this).contents().find("body").height()+30;

$(this).height(mainheight);

});

在子页面加上

$(window.parent.document).find("#iframe").load(function(){

var main = $(window.parent.document).find("#iframe");

var thisheight = $(document).height()+30;

main.height(thisheight);

});

例子:

<html lang="sv"><head>

<Meta charset="utf-8">

<title>Iframe height demo</title>

<script src="jquery.js"></script>

<style media="screen,print">

#body {

width:70em;

max-width:100%;

margin:0 auto;

}

iframe {

width:100%;

margin:0 0 1em;

border:0;

}

</style>

<script>

function setIframeHeight(iframe) {

if (iframe) {

var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;

if (iframeWin.document.body) {

iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;

}

}

};

 

window.onload = function () {

setIframeHeight(document.getElementById('iframe'));

};

</script>

</head>

<body>

<div id="body">

<h1>Iframe height demo</h1>

<h2><code>iframe</code> <strong>without</strong> height adjustment</h2>

<iframe src="child.html"></iframe>

<h2><code>iframe</code> <strong>with</strong> height adjustment</h2>

<iframe src="child.html" frameborder="0" id="iframe"></iframe>

<div id="labfooter">

</div>

</div>

 

</body>

</html>

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

猜你在找的HTML相关文章