内容更改时调整 iframe 大小 (appetize.io)(跨域)



我正在尝试自动调整嵌入另一个网站内容的iframe的大小。我还没有找到解决方案,所以我需要你的专业知识!

问题:我在网站的 iframe 中嵌入了类似移动设备的显示器 (appetize.io( 的内容。 我确实有按钮来旋转和更改手机的大小。 但是当我这样做时,iframe 的大小并没有相应地调整。因此,手机的显示被截断。 我想自动调整 iframe 的大小。

.HTML:

Device orientation: <button onclick="rotateLeft()">rotate left</button>
<button onclick="rotateRight()">rotate right</button><br/>
Device size:  <button onclick="setScale(10)">small</button> <button onclick="setScale(75)">normal</button>
<button onclick="setScale(100)">big</button>
<br/>
<iframe id="iframeid" scrolling="no" src="https://appetize.io/embed/demo_phq04c56jnvrkg0bn9w5ep4m9r?device=iphone8&orientation=portrait&scale=75&xdocMsg=true&deviceColor=white&debug=true&screenOnly=false"></iframe>

对于javascript和css,请直接查看小提琴:http://jsfiddle.net/f5u9mh8s/

尝试单击调整大小和旋转按钮,您将看到...

感谢您的帮助!

存在一个干净简单的解决方案,因为您正在使用 Appetize,它有一个可用于此目的的 API。如果 iframe 包含另一个站点,没有 API 来告诉您设备方向,则解决方案将变得不那么可靠。

在 iframe 中启动 Appetize 会话后,您可以通过 Appetize API 接收消息。Appetize 文档指示在旋转设备时将向父级发布orientationChanged消息。他们帮助提供了一个小提琴,您可以在其中测试这一点。打开浏览器控制台,单击"点击播放"按钮后,当您使用向右或向左旋转按钮旋转设备时,您将看到控制台中记录的消息,指出设备是纵向还是横向。

这意味着您可以侦听来自 iframe 的消息,当您收到orientationChanged消息时,您可以相应地调整 iframe 的大小。

例如(这只是从 Appetize 小提琴中改编代码(:

var iframe = document.getElementById('iframeid');
var messageEventHandler = function(event){
if(event.data && event.data.type == 'orientationChanged'){
if (event.data.data == 'landscape') {
iframe.height = '416px';
iframe.width = '870px';
} else if (event.data.data == 'portrait') {
iframe.height = '870px';
iframe.width = '416px';
}
}
};
window.addEventListener('message', messageEventHandler, false);

最新更新