본문 바로가기
Javascript/GMA(2302~)

23.04.20 자바스크립트 수학객체 - 새로고침 할때마다 배경 이미지 변경하기

by hyerin1201 2023. 4. 23.

HTML 과 CSS 는 따로 코드를 치지 않았다.

 

Javascript

// 바뀌어야 할 배경이미지들에 대한 정의 
// 이미지가 랜덤으로 나타나야 하는 
// 배열객체를 사용하지 않고도 만들 수 있당

// const bgImgs = ["bg-1.jpg","bg-2.jpg","bg-3.jpg","bg-4.jpg","bg-5.jpg"];
// const bgIndex = Math.floor(Math.random() * bgImgs.length);
// function changeBg() {
//   document.body.style.backgroundImage = `url(img/${bgImgs[bgIndex]})`;
// } //배열객체로 이미지의 파일명을 가져와서 url값을 주는 방법을 택했는데 아래와 같은 방법도 있다.
// changeBg();

//출력할 공간에 대한 정의
// 출력할 컨텐츠에 대한 정의

const changeBg = () => {
  const bgCount = 5;
  let randomNum = Math.ceil(Math.random() * bgCount);
  document.body.style.backgroundImage = `url(img/bg-${randomNum}.jpg)`
}

document.onload = changeBg();