Image Background

김서하·2021년 4월 20일
0
const body = document.querySelector("body") //backgrond image를 위해 body를 변수값으로 지정

const IMG_NUMBER = 3; //random값을 3으로 지정(사진이 3장이니까)

function paintImage(imgNumber){
   const image = new Image(); //어떠한 항목인지 간단한 설명을 붙이기 위한 변수이름
   image.src = `./Img/${imgNumber + 1}.jpg`; //랜덤숫자는 012이기 때문에 뒤에 +1
   image.classList.add("bgImage"); //css로 조정하기 위해서 class추가
   body.prepend(image); //body를 image에 들어가게 함
}

function genRandom(){
   const number = Math.floor(Math.random() * IMG_NUMBER); //random시에 숫자는 0,1,2 3개로 카운트
   return number; //return을 해야 해당함수가 실행 후 중단된다
}

function init(){ //실행함수
   const randomNumber = genRandom(); //랜덤 함수의 결과를 변수로 지정
   paintImage(randomNumber); //위의 랜덤값을 paint함수 변수값으로 넣어준다
}

init(); //실행!

**설명**
prepend()는 appendChild()와 거의 동일하게 동작하며
부모의 자식 요소로 추가되나 그 위치가 맨 뒤가 아닌 맨 앞에 추가되는 것이 다르다.
//
math란 모듈 존재
Math.random
Math.floor(바닥) -> 버림 
Math.ceil(천장) -> 올림



profile
개발자 지망생 서하입니당

0개의 댓글