JavaScriptで実現!iframeの高さをコンテンツに合わせて自動調整
スクロールバーを使わずに iframe の高さをコンテンツに合わせて自動調整する方法
iframe は別のウェブページを埋め込むための HTML 要素です。通常、iframe の高さは手動で設定する必要がありますが、JavaScript を使用してコンテンツに合わせて自動的に調整することもできます。
方法
この方法には、主に 2 つの方法があります。
親フレーム側の JavaScript で調整する
- 親フレーム側の HTML で、iframe に
id
属性を指定します。 - 親フレーム側の JavaScript で、
onload
イベントを使用して、iframe の高さをコンテンツに合わせて調整します。
<iframe id="my-iframe" src="https://example.com"></iframe>
const iframe = document.getElementById('my-iframe');
iframe.onload = function() {
iframe.height = iframe.contentDocument.body.scrollHeight;
};
- 子フレーム側の HTML で、
postMessage
イベントを使用して、親フレームに高さを送信します。 - 親フレーム側の JavaScript で、
message
イベントを使用して、子フレームから送信された高さを受け取り、iframe の高さを調整します。
子フレーム側の HTML
<script>
window.addEventListener('message', function(event) {
if (event.data === 'getHeight') {
const height = document.body.scrollHeight;
window.parent.postMessage(height, '*');
}
});
</script>
const iframe = document.getElementById('my-iframe');
iframe.addEventListener('message', function(event) {
if (typeof event.data === 'number') {
iframe.height = event.data;
}
});
メリット
- スクロールバーが表示されないため、ユーザーインターフェースが向上します。
- レスポンシブデザインにも対応できます。
- JavaScript が必要です。
- 複雑な実装になる場合があります。
- 上記以外にも、さまざまな方法で iframe の高さを自動調整できます。
注意
- 上記のコードはサンプルです。実際の使用には、必要に応じて修正してください。
<iframe id="my-iframe" src="https://example.com"></iframe>
const iframe = document.getElementById('my-iframe');
iframe.onload = function() {
iframe.height = iframe.contentDocument.body.scrollHeight;
};
<script>
window.addEventListener('message', function(event) {
if (event.data === 'getHeight') {
const height = document.body.scrollHeight;
window.parent.postMessage(height, '*');
}
});
</script>
// 子フレーム側で必要であればここにコードを追加
スクロールバーを使わずに iframe の高さを自動調整する他の方法
CSS の height 属性と max-height 属性を使用する
<iframe src="https://example.com" style="height: 100%; max-height: 100vh;"></iframe>
overflow: hidden; を使用する
<iframe src="https://example.com" style="overflow: hidden;"></iframe>
jQuery を使用する
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#my-iframe').height($('body').height());
});
</script>
<iframe id="my-iframe" src="https://example.com"></iframe>
iframe の onload イベントを使用する
<iframe src="https://example.com" onload="this.height = this.contentDocument.body.scrollHeight;"></iframe>
<iframe src="https://example.com"></iframe>
<script>
const iframe = document.getElementById('my-iframe');
iframe.onload = function() {
iframe.contentWindow.postMessage('getHeight', '*');
};
window.addEventListener('message', function(event) {
if (typeof event.data === 'number') {
iframe.height = event.data;
}
});
</script>
javascript html iframe