我需要一个自动调整iframe的宽度和高度的解决方案,以勉强适应其内容。关键是宽度和高度可以在iframe加载后改变。我想我需要一个事件动作来处理iframe中包含的主体尺寸的变化。
当前回答
如果iframe内容来自相同的域,这应该工作得很好。但是它确实需要jQuery。
$('#iframe_id').load(function () {
$(this).height($(this).contents().height());
$(this).width($(this).contents().width());
});
要动态调整它的大小,你可以这样做:
<script language="javaScript">
<!--
function autoResize(){
$('#themeframe').height($('#themeframe').contents().height());
}
//-->
</script>
<iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>
然后在iframe加载的页面上添加这个:
<script language="javaScript">
function resize()
{
window.parent.autoResize();
}
$(window).on('resize', resize);
</script>
其他回答
我使用这段代码自动调整所有iframe(类autoHeight)的高度,当他们加载在页面上。经过测试,它可以在IE, FF, Chrome, Safari和Opera中工作。
function doIframe() {
var $iframes = $("iframe.autoHeight");
$iframes.each(function() {
var iframe = this;
$(iframe).load(function() {
setHeight(iframe);
});
});
}
function setHeight(e) {
e.height = e.contentWindow.document.body.scrollHeight + 35;
}
$(window).load(function() {
doIframe();
});
最简单的方法是设置iframe的高度,如果你知道文档的高度是什么,如果它是固定的。
可以创建一个“幽灵般的”IFrame,就像它不存在一样。
参见http://codecopy.wordpress.com/2013/02/22/ghost-iframe-crossdomain-iframe-resize/
中描述的事件系统parent.postMessage(..) https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
这适用于所有现代浏览器!
Javascript被放置在头文件:
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
下面是iframe html代码:
<iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>
Css样式表
>
.spec_iframe {
width: 100%;
overflow: hidden;
}
在我试遍了世界上所有的方法之后,这个方法真的很适合我。
index . html
<style type="text/css">
html, body{
width:100%;
height:100%;
overflow:hidden;
margin:0px;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
$(iframe).height($(iframe).contents().find('html').height());
}
</script>
<iframe src="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>
推荐文章
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- 设置TextView文本从html格式的字符串资源在XML
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- Twitter Bootstrap 3 Sticky Footer
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器