我在div里面有一个iframe。我希望iframe的大小正好是其父div的大小。我使用以下代码来设置iframe的宽度和高度。
<iframe src="./myPage.aspx" id="myIframe"
style="position: relative;
height: 100%;
width: 100%'
scrolling='no'
frameborder='0'">
但iframe的宽度与div不同,也显示水平和垂直滚动条。
你有很多错别字。
正确的标记应该是这样的:
<iframe src="./myPage.aspx" id="myIframe" scrolling="no" frameborder="0"
style="position: relative; height: 100%; width: 100%;">
...
</iframe>
另外,如果这个框架已经有了一个ID,为什么不把它放在这样的CSS中(来自一个单独的样式表文件):
#myIframe
{
position: relative;
height: 100%;
width: 100%;
}
和HTML
<iframe src="./myPage.aspx" id="myIframe" scrolling="no" frameborder="0" > ... </iframe>
介意scrolling
和frameborder
是iframe
属性,而不是style
属性。
由于我们处于CSS3时代,您可以使用视口单元来完成此操作。这些单位允许您根据视口宽度和视口高度的百分比指定大小。这是用户的视口,也称为屏幕。但是,在我尝试过的所有主流浏览器中,如果你把一个iframe放在一个div中,这个div位于另一个div内并且相对定位,则视口单元相对于这个div。由于100个视口高度单位意味着100%高度,您可以这样做:
<div id="parent">
<div id="wrapper" style="position:relative">
<iframe style="position:absolute;top:0px;width:100%;height:100vh;" src="http://anydomain.com"></iframe>
</div>
</div>
我发现这是最好的解决方案,因为它是跨域的,并且显示完全像你想要它没有任何javascript或其他复杂的东西。
最重要的是,它适用于所有浏览器,甚至是移动浏览器(在Android和iphone上测试)!
设置动态高度 -
我更喜欢 - https://ternarylabs.github.io/porthole/
检测iframe高度变化 - 使用https://marcj.github.io/css-element-queries/
<script src="https://raw.githubusercontent.com/marcj/css-element-queries/master/src/ResizeSensor.js"></script>
<script src="https://raw.githubusercontent.com/ternarylabs/porthole/master/src/porthole.min.js"></script>
对于其余的实施,请参考要点 -
https://gist.github.com/mohandere/a2e67971858ee2c3999d62e3843889a8
(function(){
'use-strict';
//This soultion we have used - https://ternarylabs.github.io/porthole/
// example -
var iFrameId: 'guestFrame',
window.onload = function(){
// Create a proxy window to send to and receive
// messages from the iFrame
var windowProxy = new Porthole.WindowProxy(
'http://other-domain.com/', iFrameId);
var $viewPort = $('#'+iFrameId);
// Register an event handler to receive messages;
windowProxy.addEventListener(function(messageEvent) {
if( messageEvent.data.height == $viewPort.height() ){
return;
}
$viewPort.height(messageEvent.data.height);
});
Porthole.WindowProxyDispatcher.start();
};
})();
(function(){
'use-strict';
/**
* Iframe to Parent window communication
* sample iframe- <iframe id="guestFrame" name="guestFrame" src="http://other-domain.com/">
* </iframe>
* Uses https://ternarylabs.github.io/porthole/
* Uses https://marcj.github.io/css-element-queries/
*/
window.onload = function(){
var proxy = window.proxy = new Porthole.WindowProxy('http://parent-domain.com/');
proxy.addEventListener(function(messageEvent) {
// handle event
});
//Height setup
var iframeHeight = 0;
var element = document.getElementsByTagName("BODY")[0];
new ResizeSensor(element, function() {
var scrollHeight = $('body').outerHeight();
if (iframeHeight === scrollHeight) return false;
iframeHeight = scrollHeight;
proxy.post({
height: scrollHeight,
});
});
Porthole.WindowProxyDispatcher.start();
};
})();