根据内容调整iframe的大小

点点圈 提交于 2020-02-26 03:25:32

我正在开发类似iGoogle的应用程序。 使用iframe显示其他应用程序(在其他域上)的内容。

如何调整iframe的大小以适合iframe内容的高度?

我试图破译Google使用的javascript,但是它被混淆了,到目前为止,在网络上搜索毫无结果。

更新:请注意,内容是从其他域加载的,因此适用同源策略


#1楼

使用jQuery的最简单方法:

$("iframe")
.attr({"scrolling": "no", "src":"http://www.someotherlink.com/"})
.load(function() {
    $(this).css("height", $(this).contents().height() + "px");
});

#2楼

这是一种通过iframe的src属性在json中添加信息的jQuery方法。 这是一个演示,调整大小并滚动此窗口。.带有json的结果url看起来像这样... http://fiddle.jshell.net/zippyskippy/RJN3G/show/#{docHeight:5124,windowHeight:1019,scrollHeight: 571}#

这是小提琴的源代码http://jsfiddle.net/zippyskippy/RJN3G/

function updateLocation(){

    var loc = window.location.href;
    window.location.href = loc.replace(/#{.*}#/,"") 
        + "#{docHeight:"+$(document).height() 
        + ",windowHeight:"+$(window).height()
        + ",scrollHeight:"+$(window).scrollTop()
        +"}#";

};

//setInterval(updateLocation,500);

$(window).resize(updateLocation);
$(window).scroll(updateLocation);

#3楼

这有点棘手,因为您必须知道何时加载iframe页面,而当您无法控制其内容时就很难理解。 可以在iframe中添加onload处理程序,但是我过去曾尝试过这样做,并且它在浏览器中的行为也大不相同(不要猜测谁是最烦人的...)。 您可能必须将一个函数添加到iframe页面中,以执行调整大小并将某些脚本注入到内容中,以监听加载事件或调整大小事件,然后调用上一个函数。 我正在考虑向页面添加功能,因为您想确保其安全性,但是我不知道这样做会多么容易。


#4楼

我相信这件事应该起作用。

parent.document.getElementById(iFrameID).style.height=framedPage.scrollHeight;

在iframe内容上加载时将其加载。


#5楼

<html>
<head>
<script>
function frameSize(id){
var frameHeight;

document.getElementById(id).height=0 + "px";
if(document.getElementById){
    newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;    
}

document.getElementById(id).height= (frameHeight) + "px";
}
</script>
</head>

<body>

<iframe id="frame"  src="startframe.html" frameborder="0" marginheight="0" hspace=20     width="100%" 

onload="javascript:frameSize('frame');">

<p>This will work, but you need to host it on an http server, you can do it locally.    </p>
</body>
</html>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!