Animated Turtle

Javascript

명언 슬라이드 배경 이미지 바꾸기

훙구 2023. 4. 17. 14:10

...

728x90
반응형

명언이 넘어감과 동시에 배경 이미지도 같이 바뀌도록 스크립트를 추가해보겠습니다.

 

Javscript 추가하기

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;

            let randomNum = Math.floor(Math.random() * 1000);
            let url = `url("https://source.unsplash.com/random/?city&_=${randomNum}")`;
            wrapB.style.backgroundImage = url;
        }, 5000);
    });
};

추가된 javascript 알아보기

  • 기본적으로 css를 통해 wrap의 background-image를 넣어주었는데, 
  • wrap을 스크립트에서 선택자를 만들었습니다.
  • wrapB라고 만든 선택자에 wrapB.style.backgroundImage 를 사용하여 속성을 추가했습니다.
  • setInterval함수에 같이 포함하여 5초마다 한번씩 실행되게 만들었습니다.
  • backgroundImage의 url은 unsplash에서 url만 사용하여 랜덤한 이미지를 가져올 수 있는 기능을 사용했습니다.
  • (https://source.unsplash.com/random) 를 사용. ( ?city 부분은 이미지의 키워드를 의미합니다.)
  • randomNum 변수를 만들어 0부터 999의 랜덤한 숫자를 저장하고 url이 끝나는 부분에 적어주어 무작위의 이미지를 불러오도록 했습니다.

 

 

 

이상으로 명언 슬라이드에서 명언이 넘어감에 따라 배경 이미지도 같이 바뀌도록 만들어 보았습니다 !

 

728x90
반응형