Home >Web Front-end >JS Tutorial >How to Dynamically Adjust iFrame Height with JavaScript?

How to Dynamically Adjust iFrame Height with JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-31 01:32:09365browse

How to Dynamically Adjust iFrame Height with JavaScript?

Utilize JavaScript to Dynamically Adjust iFrame Height

In an effort to eliminate the need for scrollbars and create a responsive iframe that adapts to its content, consider employing the following solution:

Head Section Modification:

Introduce the following script to the section of your web page:

<script>
  function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.documentElement.scrollHeight + 'px';
  }
</script>

iFrame Modification:

Modify your iframe code as follows:

<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />

This JavaScript function retrieves the height of the iframe's content document and sets the height of the iframe accordingly. When the iframe first loads or when its content changes, the resizeIframe function is triggered, ensuring that the iframe's height is always in sync with its content.

The above is the detailed content of How to Dynamically Adjust iFrame Height with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn