LoginSignup
0
0

ResizeObserver で iframe の高さを自動調整 (2023年)

Posted at

解決方法

iframeの中身の高さに応じて、iframe自体の高さを自動調整したいことは多いが、現時点では ResizeObserverを使うのが良さそうだった。

<!doctype html>
<html>
  <body>
    <iframe src="inner.html" id="myframe"></iframe>
    <script>
      const iframe = document.getElementById('myframe');
      const resize = () => {
        iframe.style.height = iframe.contentDocument.documentElement.offsetHeight + 'px';
      }
      const observer = new ResizeObserver(resize);
      iframe.addEventListener('load', () => {
        // 手元で試したときはobserveを開始したタイミングでcallbackが呼ばれたが、
        // そうでない場合はここで `resize()` を呼び出すこと
        observer.observe(iframe.contentDocument.documentElement);
      });
    </script>
  </body>
</html>

制限

試していないが、おそらくクロスオリジンでは使えない。

その他

高さ自動調整の対象になるその他の要素は <textarea> だが、 form-sizing というCSSプロパティで自動調整されるようになるらしい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0