JavaScript_크롬 앱 만들기

서은서·2023년 3월 17일
0
post-thumbnail

3. 명언 & 배경화면

1) quotes.js 생성

quote의 array를 생성 후, random한 숫자를 이용해 array의 인덱스에서 뽑아 올 예정

const quotes =[
    {
        quote:"Nothing is more despicable than respect based on fear.",
        author:"Albert Camus"
    },
    {
        quote:"It is only with the heart that one can see rightly, what is essential is invisible to the eye.",
        author:"Antoine de Saint-Exupery"
    },
    {
        quote:"You don't live in a world all alone. Your brothers are here too.",
        author:"Albert Schweitzer"
    },
    {
        quote:"A hungry man is not a free man.",
        author:"Adlai Stevenson"
    },
    {
        quote:"One man with courage makes a majority.",
        author:"Andrew Jackson"
    },
    {
        quote:"Television has a real problem. They have no page two.",
        author:"Art Buchwald"
    },
    {
        quote:"Anything you're good at contributes to happiness.",
        author:"Bertrand Russell"
    },
    {
        quote:"Happiness is a warm puppy.",
        author:"Charles M. Schulz"
    },
    {
        quote:"I was never less alone than when by myself.",
        author:"Edward Gibbon"
    },
    {  
        quote:"A friend in power is a friend lost.",
        author:"Henry Adams"
    }
]

Math.random()

  • 0 ~ 1사이의 숫자를 랜덤하게 뽑아줌
  • but, 소수점이 많기 때문에 인덱스로 사용하기 위해 정수로 만들어줘야함
    1) Math.round() : 반올림
    2) Math.ceil() : 올림
    3) Math.floor() : 내림 --> We will use!
// index.html
...
<div id="quote">
     <span></span>
     <span></span>
</div>
...

// quotes.js
const quote = document.querySelector('#quote span:first-child');
const author = document.querySelector('#quote span:last-child');

// quote를 하나 뽑아옴
const todaysQuote = quotes[Math.floor(Math.random()*quotes.length)];

// quote와 author을 구분해서 innerText로 넣어줌
quote.innerText = todaysQuote.quote;
author.innerText = todaysQuote.author;

2) Background

javaScript에서 html에 이미지를 추가해야함(기존 html 코드에는 img가 없음)
-> createElemant를 이용해서 img를 만들어줌

const images =["0.jpeg" , "1.jpeg" , "2.jpeg"]	// 배열에 이미지의 이름을 저장함(정확하게 작성해야 함!!)

const chosenImage = images[Math.floor(Math.random()*images.length)] ; // random하게 이미지를 고름

const bgImage = document.createElement("img");   // <img>를 생성/ 생성만 됐을 뿐 아직 html에 추가되지 않음!
bgImage.src = `img/${chosenImage}`;				// <img>의 경로를 만들어 줌

document.body.appendChild(bgImage);            // html body에 img 추가하기
profile
내일의 나는 오늘보다 더 나아지기를 :D

0개의 댓글