首页 > 解决方案 > 设置 iFrame 的比例

问题描述

我正在创建一个托管游戏的网站,并且像许多网站一样,我使用精彩<iframe>标签从单独的目录中获取游戏。我正在尝试将<iframe>自身调整为 600px 宽,并让高度自动调整。

我尝试过使用 CSStransform属性,但它必须是百分比,而不是像素数。我还尝试使用 Javascript 来获取滚动高度和滚动宽度,<iframe>并将宽度设置为 600px,同时将高度设置为内容的高度。

这是我的标记、脚本和样式表。

HTML:

<div class="game-border" id="gameBack">
<iframe src="http://superfungames.com/tetris/" class="game-frame" id="gameCont" frameborder="0" scrolling="no"></iframe>
</div>
<!-- Counteract the evil effects of centering the game-border and game-frame by using position absolute !-->
<div class="breaker" id="breaker"></div>

Javascript:

var gameBack = document.getElementById('gameBack');
var breaker = document.getElementById('breaker');
var iFrame = document.getElementById('gameCont');

var iframeWin = iFrame.contentWindow || iFrame.contentDocument.parentWindow;
var iFrameHeight = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;

iFrame.style.height = iFrameHeight + 'px';

gameBack.style.height = gameBack.scrollHeight + 25 + 'px';
gameBack.style.width = gameBack.scrollWidth + 25 + 'px';

//Counteract position absolute. Additional number is like margin-top.
breaker.style.height = gameBack.scrollHeight + 10 + 'px';

CSS:

.game-frame {
width: 600px;
height: auto;
overflow: visible;
}

.game-border {
background-color: #63d68f;
position: absolute;
left: 50%;
transform: translate(-50%, 0%);
display: flex;
justify-content: center;
align-items: center;
overflow: visible;
}

我希望它<iframe>是 600px 宽和内容的高度高,但是,它是 600px 并且只显示内容的最顶部。

标签: javascripthtmlcssiframe

解决方案


iframe 标签带有宽度属性,您只需要添加width="{number_of_pixels}". 示例:<iframe src="{any_website_url}" widht="600"></iframe>,这会将宽度设置为 600 像素。

它应该适用于大多数网站(我猜),但这不适用于您正在使用的网站。似乎它使用了一些脚本将您重定向到他们的网站,而不是在 iframe 中显示它。

要解决这个问题,您可以添加属性sandbox。这将阻止网站的某些功能,例如将您重定向到他们网站的功能。示例:<iframe src="{any_website_url}" sandbox></iframe>。我不确定这是否会破坏游戏本身的任何内容。您可以尝试进行更多调查。

您的 HTML 将是这样的。无需更改 js 文件或 css 文件。

<div class="game-border" id="gameBack">
    <iframe src="http://superfungames.com/tetris/" width='600' class="game-frame" id="gameCont" frameborder="0" scrolling="no" sandbox></iframe>
</div>
    <!-- Counteract the evil effects of centering the game-border and game-frame by using position absolute !-->
<div class="breaker" id="breaker"></div> 

更多信息:


推荐阅读