如何解决CSS:如何使iframe像div?
css:如何使iframe像div?即
1) width 100%
2) Height: wrap content
3) without scroll
HTML
<body>
<div>
<iframe src="foo.html"/>
<div>
<div>
<iframe src="bar.html"/>
</div>
</body>
iframe具有高度,因此它始终具有滚动条以显示较大的内容。只能通过CSS来实现吗?
解决方法
代码 在foo.html中,需要以下javascript代码(顺便说一下,可以从任何域上的.js文件加载该代码)。
<script>
// Resize iframe to full height
function resizeIframe(height)
{
// "+60" is a general rule of thumb to allow for differences in
// IE & and FF height reporting,can be adjusted as required..
document.getElementById('frame_name_here').height = parseInt(height)+60;
}
</script>
<iframe id='frame_name_here' src='http://www.bar.html'></iframe>
在www.bar.html中:
<body onload="iframeResizePipe()">
<iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe>
<script type="text/javascript">
function iframeResizePipe()
{
// What's the page height?
var height = document.body.scrollHeight;
// Going to 'pipe' the data to the parent through the helpframe..
var pipe = document.getElementById('helpframe');
// Cachebuster a precaution here to stop browser caching interfering
pipe.src = 'foo.html?height='+height+'&cacheb='+Math.random();
}
</script>
foo.html的内容:
<html>
<!--
This page is on the same domain as the parent,so can
communicate with it to order the iframe window resizing
to fit the content
-->
<body onload="parentIframeResize()">
<script>
// Tell the parent iframe what height the iframe needs to be
function parentIframeResize()
{
var height = getParam('height');
// This works as our parent's parent is on our domain..
parent.parent.resizeIframe(height);
}
// Helper function,parse param from request string
function getParam( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
</body>
</html>
,
关于宽度和边框,可以在iframe上设置style="border:none;width:100%"
使其全宽,然后删除边框。
关于高度,取决于框架页面的位置。
如果框架页面位于相同域上,则可以使用JavaScript来完成:
<button onclick="resizeIframe();">Resize iframe</button>
<iframe src="{path on the same domain}" id="iframe" style="border:none;width:100%"></iframe>
<script>
function resizeIframe() {
var iframe = document.getElementById('iframe'),height = iframe.contentWindow.document.body.scrollHeight;
iframe.style.height = height + 'px';
}
</script>
只要带框架的页面位于同一个域中,此代码段即开即用。
如果带有框架的页面位于不同的域(mysite.com与youtube.com)上,则无法从外部访问iframe,因为一种安全措施。
如果不存在这种安全措施,那么恶意网页可能会做坏事,例如在网站上窃取您的凭据。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。