Random Quotes & Background

김민재·2021년 7월 2일
0

Gotcha JavaScript!

목록 보기
10/45

Math.random

-array, 배열에서 랜덤하게 element를 골라내야한다. Math.random();은 임의 숫자를 리턴해준다.
-여기에 *num을 작성하면 0~num까지 사이의 숫자를 소수로 리턴해준다. 따라서 배열의 길이를 num값으로 넣어주면 0부터 배열의 길이 사이에 있는 숫자를 얻을 수 있다.

> 소수값을 정수로 바꾸는 데 3가지 방법이 있다

1>Math.round(숫자), 반올림해주는 메소드이다.
2>Math.ceil(숫자), 숫자를 천장까지 높여준다. 즉 1.0은 1이지만 1.01은 2가된다.
3>Math.floor(숫자), 바닥까지 숫자를 내려준다. 1.01은 1이되고 1.99도 1이 된다.

<script>
const quotes = [
  {
    quote:"“Be yourself; everyone else is already taken.”",
    author:"― Oscar Wilde"
  }, 
  //명언 배열 모은
  //...
const quote = document.querySelector("#quote span:first-child"); 
const author = document.querySelector("#quote span:last-child"); 
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
</script>

-마찬가지로 img를 랜덤하게 가져오기 위해서 여러 이미지들을 담은 리스트를 변수에 담준 뒤
Math함수를 통해 무작위로 리스트 갯수 중 하나의 값을 가져오고 값을 floor을 통해 정수로 바꿔준다.

  • createElement("인자")메소드를 통해 JS에서 HTML의 요소를 만들어준다.

    -인자로 값을 전달하면 해당 태그가 만들어지고 img태그를 만든 뒤 img태그의 src 속성 값을 생성했던 배열의 무작위 변수, chosenImg를 전달하여 넣어준다.
  • 마지막으로 생성한 bgImg를 appendChild 메소드를 통해서 body태그의 마지막 자식 요소로 넣어준다.
    prependChild 메소드를 사용하면 가장 위에 자식요소로 넣어줄 수 있다.
<script>
const backgroundImg = [
  "background.1.jpeg",
  "background.2.jpeg",
  "background.3.jpeg",
  "background.4.jpeg",
  "background.5.jpeg",
  "background.6.jpeg"
]
const chosenImg = backgroundImg[Math.floor(Math.random() * backgroundImg.length)];
const bgImg = document.createElement("img");
bgImg.src = `../../img/${chosenImg}`
console.log(bgImg)
document.body.appendChild(bgImg)
</script>
profile
자기 신뢰의 힘을 믿고 실천하는 개발자가 되고자합니다.

0개의 댓글