끄적끄적 코딩
article thumbnail
Published 2020. 12. 23. 19:50
[JavaScript] 배경이미지 설정 JavaScript
728x90

페이지를 들어갈 때마다 랜덤하게 배경이 바뀌는 것을 구현

<html />
<!-- index.html --> <!DOCTYPE html> <html> <head> <title>backgroundImg</title> <link rel="stylesheet" href="index.css" /> </head> <body> <script src="bg.js"></script> </body> </html>

 

<javascript />
//bg.js const body = document.querySelector("body"); const IMG_NUMBER = 5; function paintImage(imgNumber) { const image = new Image(); image.src = `images/${imgNumber + 1}.jpg`; // 가져올 image경로 지정 image.classList.add("bgImage"); // image에 bgImage 클래스 추가 body.appendChild(image); // body의 자식에 image추가 } function genRandom() { const number = Math.floor(Math.random() * IMG_NUMBER); return number; } function init() { const randomNumber = genRandom(); paintImage(randomNumber); } init();

Math.floor - 소수점 버림
Math.random - 0 ~ 0.999... 의 값 랜덤 반환

 

<css />
index.css body { background-color: #2c3e50; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .bgImage { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; animation: fadeIn 0.5s linear; }

.

검색 태그