HTML
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>valila js</title>
</head>
<body>
<form id="login-form" class="hidden">
<input
required
maxlength="15"
type="text"
placeholder="what is your name?"
/>
<input type="submit" value="Log in" />
</form>
<h2 id="clock">00:00:00</h2>
<h1 id="greeting" class="hidden"></h1>
<div id="quote">
<span></span>
<span></span>
</div>
<script src="js/greetings.js"></script>
<script src="js/clock.js"></script>
<script src="js/quotes.js"></script>
</body>
</html>
자바스크립트에 10개의 명언 배열 만들기
const quotes = [
{
quote: "꿈을 계속 간직하고 있으면 반드시 실현할 때가 온다.",
author: "괴테",
},
{
quote: "닫혀있기만 한 책은 블록일 뿐이다.",
author: "토마스 풀러",
},
{
quote: "오늘이라는 날은 두 번 다시 오지 않는다는 것을 잊지 말라.",
author: "단테",
},
{
quote: "고난이 지나면 반드시 기쁨이 스며든다.",
author: "괴테",
},
{
quote: "그대의 하루하루를 그대의 마지막 날이라고 생각하라.",
author: "호라티우스",
},
{
quote: "변명 중에서도 가장 어리석고 못난 변명은 시간이 없어서라는 변명이다.",
author: "에디슨",
},
{
quote: "어디를 가든지 마음을 다해 가라.",
author: "공자",
},
{
quote: "자신감은 위대한 과업의 첫째 요건이다.",
author: "사무엘 존슨",
},
{
quote: "승리는 가장 끈기있는 자에게 돌아간다.",
author: "나폴레옹",
},
{
quote: "시간과 정성을 들이지 않고 얻을 수 있는 결실은 없다.",
author: "그라시안",
}
];
const quote = document.querySelector("#quote span:first-child");
const author = document.querySelector("#quote span:last-child");
console.log(quotes[Math.floor(Math.random() * 10)]);
문제점 : Math에 10을 사용해서 명언을 호출할 경우 추후에 명언 추가시 숫자도 바꿔줘야하는 불편함 발생
[문제 해결] Array.length 사용
console.log(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)];
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;
HTML 문서에서 지정한 두개의 span(quote, author) 태그에 innerText를 변경하는 방식으로 랜덤 명언 호출
랜덤 배경화면
- 자바스크립트에서 이미지를 불러올 경우 이미지 파일의 이름과 동일하게 작성
사진 랜덤으로 불러오기
const images = ["0.jpg", "1.jpg", "2.jpg"]; // 사진과 이름 같아야 함
const chosenImage = images[Math.floor(Math.random() * images.length)];
HTML에 이미지를 불러온 자바스크립트를 보내야함
➝ document.createElement 사용
HTML에 보내기
const images = ["0.jpg", "1.jpg", "2.jpg"];
const chosenImage = images[Math.floor(Math.random() * images.length)];
const bgImage = document.createElement("img");
bgImage.src = `img/${chosenImage}`;
document.body.appendChild(bgImage)
document.body.appendChild() : body의 가장 뒤에 HTML 추가하는 것
prepend : 가장 위에 추가
'JavaScript' 카테고리의 다른 글
[노마드 코더] Math(random, round, ceil, floor) (1) | 2023.11.17 |
---|---|
[노마드 코더] 시계 구현하기 (0) | 2023.11.17 |
[노마드 코더] Padstart, 숫자 ➝ 문자열 변환 (0) | 2023.11.17 |
[노마드 코더] Date 값 구하기(날짜, 시간) (0) | 2023.11.15 |