Animated Turtle

Javascript

명언 슬라이드

훙구 2023. 4. 15. 18:12

...

728x90
반응형

Json파일을 불러와 계속 넘어가는 명언 만들기

시간이 지남에 따라 계속 명언이 바뀌는 효과를 만들어보도록 하겠습니다.

 

HTML 작성하기

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quest415</title>
    <link href="https://webfontworld.github.io/yangheeryu/GowunBatang.css" rel="stylesheet">
</head>
<body>
    <div id="wrap">
        <div class="saying__box">
            <div class="saying">
                <h3></h3>
                <span></span>
                <p></p>
            </div>
        </div>
    </div>
</body>
</html>

HTML 정리해보기

  • html문서 상의 구조는 배경이미지를 넣어 전부를 감쌀 wrap부분과
  • 명언이 들어갈 상자인 saying__box 부분,
  • 명언 번호, 문구, 저자를 포함하는 saying 부분으로 만들었습니다.

CSS 작성하기

* {
    margin: 0;
    padding: 0;
}
body {
    background-color: #000007
}
#wrap {
    width: 80%;
    height: 100vh;
    margin: 0 auto;
    background-image: url("img/city.jpg");
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
}
.saying__box {
    width: 400px;
    height: 40vh;
    border-radius: 30px;
    background-color: rgba(0, 0, 0, 0.6);
    box-shadow: 0 0px 100px rgb(59, 59, 59);
    margin: 0 auto;
    transform: translateY(50%);
}
.saying h3 {
    color: #5e5e5e;
    padding: 10px;
    font-weight: normal;
    font-family: "GowunBatang";
}
.saying span {
    position: absolute;
    top: 20%;
    display: inline-block;
    text-align: center;
    padding: 0 20px;
    font-size: 18px;
    line-height: 2;
    color: #fff;
    font-family: "GowunBatang";
}
.saying p {
    position: absolute;
    font-size: 14px;
    bottom: 20px;
    right: 5px;
    padding: 20px 30px 10px 0;
    line-height: 2;
    color: #cfcfcf;
    font-family: "GowunBatang";
}

CSS 정리해보기

  • body부분에 백그라운드로 이미지를 넣었습니다.
  • saying__box의 백그라운드 컬러에 투명도를 넣어 뒤에 이미지가 비치도록 했습니다.
  • 웹폰트 링크를 걸어 적용했습니다.

Javascript 작성하기

// 선택자
const sayH = document.querySelector(".saying h3");
const saySpan = document.querySelector(".saying span");
const sayP = document.querySelector(".saying p");

// 명언이 들어갈 빈 배열
let quoteAll = [];

// 명언 불러오기
const quotesData = () => {
    fetch("json/quest415.json")
    .then(quotes => quotes.json())
    .then(saying => {
        // console.log(saying);
        quoteAll = saying.quotes.map((el, index) => {
            const formattedSaying = {
                id : el.id,
                quote : el.quote,
                author : el.author
            }
            // console.log(formattedSaying)
            return formattedSaying;
        });
        // 명언 출력 실행문
        updateQuote();
    })
    .catch((err) => console.log(err));
}
// 명언 불러오기 실행문
quotesData();

// 명언 출력
const updateQuote = () => {
    quoteAll.forEach(() => {
        let index = 0;
        // 기본 첫 화면에 1번 문구 띄우기
        sayH.innerHTML = `${quoteAll[0].id}.`
        saySpan.innerHTML = quoteAll[0].quote;
        sayP.innerHTML = quoteAll[0].author;
        // 순차적으로 문구 띄우기
        setInterval(() => {
            // index = Math.floor(Math.random() * quoteAll.length);
            index = (index + 1) % quoteAll.length;
            sayH.innerHTML = `${quoteAll[index].id}.`
            saySpan.innerHTML = quoteAll[index].quote;
            sayP.innerHTML = quoteAll[index].author;
        }, 5000);
    });
};

Javascript 정리해보기

  • 명언번호, 내용, 저자가 들어갈 부분을 선택하는 변수를 만들어줍니다.
  • json파일에서 받아와 내용을 넣어줄 빈 배열을 만들어줍니다.
  • json파일에서 내용을 받아오는 함수를 만들어줍니다.
  • quotesData() 함수
  • "json/quest415.json" 파일을 가져옵니다.
  • quotes에 json파일 형식으로 저장합니다.
  • 안에 들어있는 내용물을 saying이라 저장합니다.
  • quoteAll 에 (빈 배열) saying의 quotes (saying은 객체형식이며 키 "quotes"에 배열이 들어있습니다.)에 map() 메서드를 사용합니다.
  • 변수 formattedSaying(json파일의 내용을 가공)에 el(배열 saying.quotes 각각의요소)의 id, quote, author를 객체 형식으로 저장합니다.
  • map()메서드를 통해 변환된 배열을 return문을 사용하여 formattedSaying에 할당합니다.
  • updateQuote() 함수
  • quoteAll에 forEach를 사용합니다.
  • index에 0을 저장합니다.
  • setInterval함수를 사용해 다음의 내용을 5초마다 반복합니다.
  • index에 (index+1) % quoteAll.length 를 저장하면 순차적으로 출력이 가능합니다.
  • index에 Math.floor(Math.random() * quoteAll.length)를 저장하면 무작위 순서로 출력이 가능합니다.
  • sayH 에 quoteAll[index].id 값을 출력합니다.
  • saySpan 에 quoteAll[index].quote 값을 출력합니다.
  • sayP 에 quoteAll[index].author 값을 출력합니다.

 

 

 

이상으로 json파일에 저장되어 있는 명언들을 계속해서 출력하는 스크립트에 대해 알아보았습니다 !

728x90
반응형