Javascript/문제 풀이

자바스크립트 : 마무리 문제를 풀어 봅시다 4-1탄

아라라_ 2023. 4. 17. 18:53

“ 지연되는 프로젝트에 인력을 더 투입하면 오히려 더 늦어진다. ”

Frederick Philips Brooks
Mythical Man-Month 저자
728x90

이번은 명언이 10초에 한번씩 랜덤으로 바뀌는 스크립트를 짰던것을 이번엔 unsplish api을 활용하여 랜덤으로 배경이미지 변경되는 스크립트를 추가하였습니다. 그에 맞게 css도 수정하였습니다.


CSS

* {
    margin: 0;
    padding: 0;
    /* background-color: #000; */
}
body {
    background-size: cover;
    background-repeat: no-repeat;
    width: 100%;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}
body::before {
    content: '';
    position: absolute;
    left: 0;top: 0;
    width: 100%;
    height: 100vh;
    z-index: -1;    
}
.result__wrap {
    font-family: "GmarketSans";
    width: 600px;
    height: 400px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #000;
    /* border: 1px solid #fff; */
    border-radius: 20px;
    border: 1px solid rgba(255, 255, 255, 0.8);
    background-color: rgba(255, 255, 255, 0.2);
    padding: 60px;
    backdrop-filter: blur(5px)
}
.result__wrap::after {            
    content: '';
    position: absolute;
    width: 600px;
    height: 400px;
    padding: 60px;
    border-radius: 20px;
    box-shadow: 10px 10px 25px rgba(57, 57, 57, 0.5);
}
#result {
    /* width: 800px; */
    line-height: 2;
}
.quote {
    font-size: 30px;
}
.author {
    font-size: 20px;
}
  • 전체 선택자 (*): 웹 페이지의 모든 요소에 대해 아래의 CSS 속성을 적용합니다. 여기서는 기본적으로 마진과 패딩을 0으로 설정합니다.
  • Body: 웹 페이지의 본문(body) 요소에 대한 스타일을 정의합니다. 배경 크기를 cover로 설정하고, 반복(repeat)을 없애고, 가로 세로 중앙에 정렬하도록 설정합니다.
  • Body::before: 본문 요소의 전경에 위치한 가상 요소(before)에 대한 스타일을 정의합니다. 가상 요소를 사용하여 배경을 생성하고, 전체 화면 크기에 해당하는 가상 요소를 생성합니다. 이를 통해 흐릿한 효과를 만듭니다.
  • .result__wrap: 클래스 이름이 result__wrap인 요소에 대한 스타일을 정의합니다. 폰트 패밀리를 "GmarketSans"로 설정하고, 너비와 높이를 600px와 400px로 설정합니다. 요소를 가운데 정렬하도록 설정하고, 배경색을 투명한 흰색으로 설정하고 투명도를 조절하여 흐릿한 효과를 만듭니다. 또한, 테두리를 둥글게 처리하고, 그림자를 추가합니다.
  • .result__wrap::after: 클래스 이름이 result__wrap인 요소의 가상 요소(after)에 대한 스타일을 정의합니다. 가상 요소를 사용하여 그림자를 추가하고, 테두리를 둥글게 처리합니다.
  • #result: 아이디 이름이 result인 요소에 대한 스타일을 정의합니다. 폭을 800px로 설정하고, 줄 높이를 2로 설정합니다.
  • .quote와 .author: 클래스 이름이 quote와 author인 요소에 대한 스타일을 정의합니다. 각각 폰트 크기를 30px와 20px로 설정합니다.

SCRIPT

const mainResult = document.querySelector("#result");
const resultQuote = mainResult.querySelector(".quote");
const resultAuthor = mainResult.querySelector(".author");

let resultAll = [];

const dataresult = (value) => {
    fetch("json/dummy01.json")
    .then(res => res.json())
    .then(items => {
        const randomIndex = Math.floor(Math.random() * items.length);
        // const forPhrase = {
        //     quote: items[0].quote,
        //     author: items[0].author
        // };
        resultQuote.textContent = items[randomIndex].quote;
        resultAuthor.textContent = "- "+items[randomIndex].author;
        // document.body.style.transition= "all 2s";
    })

    .catch((err) => console.log(err));
};

const randomBg = (value) => {
    fetch("https://source.unsplash.com/random/?yellow")
    .then(res => {
        document.body.style.backgroundImage = `url(${res.url})`
        document.body.style.transition= "ease 2s";

    })
    .catch((err) => console.log(err));
};

dataresult();
randomBg();
setInterval(randomBg, 10000);
setInterval(dataresult, 10000);



// console.log(items);
  • const randomBg = (value) => {...}: randomBg라는 이름의 화살표 함수를 정의합니다. 이 함수는 fetch를 사용하여 " https://source.unsplash.com/random/?yellow "이라는 주소에서 랜덤한 배경 이미지를 가져와서 document.body의 배경 이미지로 설정합니다.
  • fetch(" https://source.unsplash.com/random/?yellow "): fetch 함수를 사용하여 " https://source.unsplash.com/random/?yellow " 주소에 GET 요청을 보냅니다. 이 주소에서는 랜덤한 배경 이미지를 가져올 수 있습니다.
  • .then(res => {...}): fetch 요청이 성공하면 반환된 res 객체를 사용하여 콜백 함수를 실행합니다. 콜백 함수 내에서는 document.body.style.backgroundImage를 사용하여 res.url을 배경 이미지로 설정합니다. res.url은 fetch 요청으로 가져온 이미지의 URL입니다.
  • document.body.style.transition= "ease 2s";: document.body의 배경 이미지 변경에 대한 트랜지션 효과를 설정합니다. 이 경우, 2초 동안 "ease" 타이밍 함수를 사용하여 부드럽게 변경됩니다.
  • .catch((err) => console.log(err));: fetch 요청이 실패하면 발생한 오류를 콘솔에 출력합니다.
  • randomBg();: randomBg 함수를 호출하여 초기에 배경 이미지를 설정합니다.
  • setInterval(randomBg, 10000);: 10초마다 randomBg 함수를 호출하여 배경 이미지를 업데이트합니다. setInterval 함수는 주어진 시간 간격마다 함수를 반복적으로 실행하는 기능을 제공합니다. 이 경우, 10초마다 randomBg 함수를 호출하여 배경 이미지를 변경합니다.

이렇게  랜덤으로 이미지를 받아오는 스크립트를 추가하였습니다.