响应式地在iframe中嵌入Bootstrap网页

5
我正在开发一款SaaS应用程序,它基本上为客户提供了一个完整的网页。客户可以通过http://client.myapp.com访问他们的页面。然而,我希望允许客户轻松地将此页面嵌入到他们的网站中。目前,我只提供了一个iframe嵌入代码和样式表来重置body标签的边距。
<head>
<style type="text/css">
html { overflow: auto; }
html, body, div, iframe { margin: 0px; padding: 0px; height: 100%; border: none; }
iframe { display: block; width: 100%; border: none; overflow-y: auto; overflow-x: hidden; }
</style>
</head>

<body>
<iframe id="myapp" name="myapp" src="https://client.myapp.com" frameborder="0" marginheight="0" marginwidth="0" width="100%" height="100%" scrolling="auto"></iframe>
</body>

然而,当他们包含iframe时,页面不再具有响应性。在使用iframe(或任何其他您可能建议的方法)时,如何复制原始网页的响应性?
3个回答

8
我找到了两个解决问题的方案: 方案1:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>body { margin: 0px; } .embed-container { position: relative; padding-bottom: 100%; height: 0; overflow: hidden; max-width: 100%; min-height: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style>
</head>
<body>
<div class='embed-container'><iframe src='https://client.myapp.com' style='border:0;'></iframe></div>
</body>

解决方案2:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
/* Using http://npr.github.io/responsiveiframe/ */
<script src="jquery.responsiveiframe.js"></script>

<script type='text/javascript'>
$(function() {
  $('iframe').responsiveIframe({xdomain: '*'});
});
</script>

<style>
body {
  margin: 0;
}
</style>
</head>

<body>

<iframe src='https://client.myapp.com' style='border:0; width: 100%; height: 100%;'></iframe>

</body>

到目前为止,它们在桌面浏览器(Chrome、Firefox)和我的移动设备上(Android 4)都能正常工作。

2
添加类似如下内容
@media screen and (min-width: 768px) {
  iframe{    
    min-width:768px;
    }
}

@media screen and (min-width: 992px) {
  iframe{ 
    min-width:992px;
    }
}

@media screen and (min-width: 1200px) {
  iframe{    
    min-width:1200px;
    }
}

将下面的媒体查询添加到您的 CSS 文件中。

这些媒体查询会导致 iframe 宽度与包含屏幕宽度相匹配。


0
确保您在iframe的头部中使用了以下代码:<meta name="viewport" content="width=device-width, initial-scale=1.0">

是的,谢谢,我也是这么想的,这就是为什么我在上面包含了两个答案。 - Anton Evangelatov
大多数情况下,我们使用iframe的原因是我们无法控制内容。更改标题似乎相当无害,但嵌入银行网站并修改其JavaScript,这就不再是无害的了。 - the Hampster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接