回答編集履歴

6

理由

2022/10/21 17:11

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -24,3 +24,12 @@
24
24
  console.log(headerifr.contentWindow.document.body.scrollHeight);
25
25
  };
26
26
  ```
27
+
28
+ ---
29
+
30
+ widthをJSで指定したらうまくいかない理由ですが、推測なんですけども、
31
+ せっかく`<iframe>`タグの中で`width="100%"`と書いて可変にしているのに、ページロード時、JSでwidthをpxで指定し固定幅としました。
32
+ ですので、それ以降画面サイズを変えてもiframeのwidthが変わることがなく、つまりheightも変わりません。
33
+
34
+ JSでwidthをpx指定する記述を削除すれば`width="100%"`のおかげで横幅は可変になりますので、iframeの横幅の変化に応じて高さも変化してくれます。
35
+

5

add

2022/10/21 07:59

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -12,4 +12,15 @@
12
12
  iFrame.style.height = `${height}px`; // iFrameの高さを変更
13
13
  }
14
14
  ```
15
+ ---
15
16
 
17
+ 質問者様のコードの場合も、widthのサイズ変更をする記述を削除したらうまく動きます。
18
+ ```diff
19
+ function resizeElement() {
20
+ //要素を取得してから、幅と高さを取得
21
+ let headerifr = document.getElementById("headerifr");
22
+ - headerifr.style.width = headerifr.contentWindow.document.body.scrollWidth + "px";
23
+ headerifr.style.height = headerifr.contentWindow.document.body.scrollHeight + "px";
24
+ console.log(headerifr.contentWindow.document.body.scrollHeight);
25
+ };
26
+ ```

4

誤字

2022/10/21 07:44

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -13,5 +13,3 @@
13
13
  }
14
14
  ```
15
15
 
16
- 質問者様は、iFrameの中のbodyの高さを取得して、同じくiFrameの中のbodyにその高さを適用されているので、何も変化なしでした。
17
-

3

JSに変更

2022/10/21 07:43

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -1,11 +1,17 @@
1
- ~~CSSだけでできると思います!~~
1
+ widthは既に可変なので、heightだけJS変更してあげたらいいと思います
2
2
 
3
- ```css
3
+ ```javascript
4
+ window.addEventListener('load', resizeIframe); // ページ読み込み時に実行
5
+ window.addEventListener('resize', resizeIframe); // 画面サイズ変更時に実行
6
+
4
- iframe {
7
+ function resizeIframe() {
8
+ const iFrame = document.querySelector('#headerifr'); // <iFrame>要素を取得
9
+ const ifrBody = iFrame.contentWindow.document.querySelector('body'); // iFrameの中の<body>要素を取得
5
- aspect-ratio: 2 / 1; /* 横:縦=2:1 */
10
+ const height = ifrBody.scrollHeight; // bodyの高さを取得
11
+
12
+ iFrame.style.height = `${height}px`; // iFrameの高さを変更
6
13
  }
7
14
  ```
8
15
 
9
- ~~お好きな比率入れてくさい。~~
16
+ 質問者様は、iFrameの中のbodyの高さ取得し、同じiFrameの中のbodyにその高を適用されてるので、何も変化なしでした
10
17
 
11
- 修正中

2

修正

2022/10/21 07:28

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -1,4 +1,4 @@
1
- CSSだけでできると思います!
1
+ ~~CSSだけでできると思います!~~
2
2
 
3
3
  ```css
4
4
  iframe {
@@ -6,4 +6,6 @@
6
6
  }
7
7
  ```
8
8
 
9
- お好きな比率を入れてください。
9
+ ~~お好きな比率を入れてください。~~
10
+
11
+ 修正中

1

誤字

2022/10/21 07:26

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```css
4
4
  iframe {
5
- aspect-ratio: 2 / 1; /* 縦:横=2:1 */
5
+ aspect-ratio: 2 / 1; /* 横:縦=2:1 */
6
6
  }
7
7
  ```
8
8