JS: 노마드 코더 6강 정리

ChoHyerin·2023년 5월 17일
0

Javascript

목록 보기
5/7

6.0 Quotes

1) Math.random()
: 0-1까지 사이 아무 숫자 랜덤 출력

2) Math.floor()
: 소수점 이하를 버림

3) Math.ceil()
: 소수점 이하를 올림

4) Math.round()
: 소수점 이하를 반올림

index.html

    <h2 id="clock">00:00:00</h2>
    <h1 class="hidden" id="greeting"></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>

quotes.js

const quotes = [
    {
      quote: "The way to get started is to quit talking and begin doing.",
      author: "Walt Disney",
    },
    {
      quote: "Life is what happens when you're busy making other plans.",
      author: "John Lennon",
    },
    {
      quote:
        "The world is a book and those who do not travel read only one page.",
      author: "Saint Augustine",
    },
    {
      quote: "Life is either a daring adventure or nothing at all.",
      author: "Helen Keller",
    },
    {
      quote: "To Travel is to Live",
      author: "Hans Christian Andersen",
    },
    {
      quote: "Only a life lived for others is a life worthwhile.",
      author: "Albert Einstein",
    },
    {
      quote: "You only live once, but if you do it right, once is enough.",
      author: "Mae West",
    },
    {
      quote: "Never go on trips with anyone you do not love.",
      author: "Hemmingway",
    },
    {
      quote: "We wander for distraction, but we travel for fulfilment.",
      author: "Hilaire Belloc",
    },
    {
      quote: "Travel expands the mind and fills the gap.",
      author: "Sheda Savage",
    },
  ];
  
const quote = document.querySelector("#quote span:first-child"); //첫번째 span태그
const author = document.querySelector("#quote span:last-child"); //두번째 span태그
const todaysQuote = quotes[Math.floor(Math.random() * quotes.length)];
//랜덤함수의 값에서 *10을 하면 1부터 10사이의 값을 구할 수 있음 -> 3.55534554, 6.3453345
//소수점 이하를 없애기 위해 Math.floor사용
//quotes.length -> quotes배열의 길이 나타냄
  
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;

배열.length == 배열의 길이

새로고침 후


6.1 Background

1) document.createElement("img")
: createElement element(요소) 생성

2) document.body.appendChild()
: appendChild 선택한 요소에 자식요소 추가


js/background.js

const images = ["0.jpg", "1.jpg", "2.jpg", "3.jpg", "4.jpg"];

const chosenImage = images[Math.floor(Math.random() * images.length)];

const bgImage = document.createElement("img"); //이미지 태그 추가

bgImage.src = `img/${chosenImage}`; //이미지태그에 경로 설정

document.body.appendChild(bgImage);
//<img src="img/0.jpg"> 이런식으로 생성됨


+ JS에서 html 요소를 생성

createElement(" ")
ex) document.createElement("img")일 경우 html 내에 img 태그를 생성

0개의 댓글