이 부분 중요! 앞쪽에 quotes배열을 넣어주고 그 길이 만큼 곱해서 랜덤 수를 지정해주었다. 그리고 Math.floor
함수를 넣어서 소숫점 자리를 내려 주었다. 그러면 quotes배열의 해당값이 변수 todaysQuote에 나오고 innerText
로 화면에 보여지게 된다.
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)]
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)];
//Math.round(1.9) 반올림
//Math.ceil(1.1) 올림
//Math.floor(1.9) 내림
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
명언이 나오게 한 것과 거의 똑같다. 이번엔 src를 넣어주는 것이 조금 다를뿐이다.
이번에는 js에서 html에 Element를 추가해주었는데 document.createElement
를 써주면 된다. body
에 뒤쪽에 추가해주기 위해 appendChild
를 썼다.
const images = [
"01.jpg",
"02.jpg",
"03.jpg",
"04.jpg",
"05.jpg",
"06.jpg",
"07.jpg",
];
const chosenImage = images[parseInt(Math.random() * images.length)];
const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImage}`;
document.body.appendChild(bgImage);
완성한 모습은 이렇다! 새로고침 할 때마다 다른 명언, 다른 사진이 나온다. (중복도 있음)