実現したいこと
- javascriptでwebページ内の特定のimage要素を背景として表示する機能を動作するようにする
前提
JavaScriptで、以下のhtml構成を下記の要件で動作させたい。
html構成は以下の通りです。
<div class="wc_back"> <div class="wc_back_img"> <img src="画像のURL" /> </div> <div class="wc_back_txt"> <div><p>テキストの内容</p></div> </div> </div>作成するjavascriptsの要件は以下の通りです。
1."wc_back_img"を親に持つ画像を画面幅一杯で表示してください。
2.表示した際の余白は上下左右すべて0にしてください。
3.画面サイズが変わったら自動でリサイズしてください。
4.画像の高さは最低390pxにしてください。
5.表示した画像に"wc_back_txt"を親に持つテキストを被せてください。
6.テキストの表示位置は、画像の左上にしてください。
7."wc_back_center"を追加持つテキストは画像中央に表示してください。
8.上記html構成が複数存在する場合は全てに適用してください。
発生している問題・エラーメッセージ
4.画像の高さは最低390pxにしてください。 が反映されない
該当のソースコード
JavaScript
1// image要素を背景として使う関数 2function useImageAsBackground() { 3 // wc_backというクラスを持つすべてのimage要素を取得 4 const imageElements = document.querySelectorAll('.wc_back img'); 5 const textElements = document.querySelectorAll('.wc_back_txt'); 6 7 if (imageElements.length === textElements.length) { 8 // wc_back要素の数だけループ処理を行う 9 for (let i = 0; i < imageElements.length; i++) { 10 const imageElement = imageElements[i]; 11 const textElement = textElements[i]; 12 13 // 取得したimage要素の親要素に背景要素を作成 14 const parentElement = imageElement.parentNode; 15 const backgroundElement = document.createElement('div'); 16 backgroundElement.classList.add('background-element'); 17 18 // 取得したimage要素のパスを取得して背景として設定 19 const imagePath = imageElement.getAttribute('src'); 20 backgroundElement.style.backgroundImage = `url(${imagePath})`; 21 22 // 取得したimage要素を非表示にする 23 imageElement.style.opacity = '0'; 24 25 // 最低の高さを指定するための変数 26 const minHeight = 390; 27 28 // 背景要素に対して適用するCSSを設定 29 backgroundElement.style.position = 'absolute'; 30 backgroundElement.style.top = '0'; 31 backgroundElement.style.left = '0'; 32 backgroundElement.style.width = '100%'; 33 backgroundElement.style.height = '100%'; 34 backgroundElement.style.backgroundSize = 'cover'; 35 backgroundElement.style.backgroundPosition = 'center'; 36 backgroundElement.style.backgroundRepeat = 'no-repeat'; 37 38 // テキスト要素を配置 39 textElement.style.position = 'relative'; 40 textElement.style.zIndex = '1'; 41 42 // 背景要素とテキスト要素を親要素に追加 43 parentElement.appendChild(backgroundElement); 44 45 // 背景要素の下部の余白を0に設定 46 parentElement.style.paddingBottom = '0'; 47 48 // 背景画像の読み込みが完了した後に背景要素の高さを設定する 49 imageElement.addEventListener('load', () => { 50 const textHeight = textElement.offsetHeight; 51 const backgroundHeight = Math.max(textHeight, minHeight); 52 backgroundElement.style.height = `${backgroundHeight}px`; 53 54 // 背景要素の下部の余白を0に設定 55 parentElement.style.paddingBottom = '0'; 56 }); 57 } 58 } 59} 60 61// HTMLの要素が読み込まれた後に実行する処理 62window.addEventListener('DOMContentLoaded', () => { 63 useImageAsBackground(); 64});
試したこと
最低の高さを指定するための変数を調整した
補足情報(FW/ツールのバージョンなど)
イメージがわかないので図示できませんか?

