바닐라 JS) 16. 랜덤 배경 이미지 만들기

송민경's avatar
Sep 02, 2024
바닐라 JS) 16. 랜덤 배경 이미지 만들기

1. background.js 만들기

  • index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> </head> <body> <form class="login-form hidden" id="login-form"> <input required maxlength="15" type="text" placeholder="What is your name?" /> </form> <h2 id="clock">00:00:00</h2> <h1 class="hidden" id="greeting" ></h1> <div id="quote"> <span></span> <span></span> </div> <script src="js/greetings.js"></script> <script src="js/clock.js"></script> <script src="js/quotes.js"></script> <script src="js/background.js"></script> </body> </html>
 

2. 이미지 준비하기

  • img 폴더 만들고 내부에 이미지 넣기
notion image
 

3. image 랜덤으로 선택하기

const images = ["desk.jpeg", "sky.jpeg", "simple.png"]; const choseImage = images[Math.floor(Math.random() * images.length)]; console.log(choseImage);
notion image
notion image
 

4. 배경 이미지로 적용하기

const images = ["desk.jpeg", "sky.jpeg", "simple.png"]; const choseImage = images[Math.floor(Math.random() * images.length)]; const bgImage = document.createElement("img"); // img 추가 bgImage.src = `img/${choseImage}`; // 이미지 경로 설정 console.log(bgImage);
notion image
notion image
 

5. body 내부에 추가하기

const images = ["desk.jpeg", "sky.jpeg", "simple.png"]; const choseImage = images[Math.floor(Math.random() * images.length)]; const bgImage = document.createElement("img"); // img 추가 bgImage.src = `img/${choseImage}`; // 이미지 경로 설정 document.body.appendChild(bgImage); //body내부에 추가하기
notion image
notion image
Share article
RSSPowered by inblog