[DAY - 57] class 예제 연습

2023. 5. 23. 19:55·🔥 부트캠프-웹 개발 🔥/JavaScript_advanced

1) class 연습 예제 #1

 

<body>
    <h1> test </h1>
    <div class="content">
    </div>
    <script>
        const content = document.querySelector('.content');
        const make = (elem, title = 'Info') => {
            elem.innerHTML += `
            <div class="box">
            <h2>${title}</h2>
            <strong>세부 타이틀</strong>
            </div>
            `
        };
        const getInfo = () => {
            return `
            <div class="info">
            일정관리 세부 리스트
            </div>
            `
        };
        content.innerHTML += getInfo();
        for (let i = 1; i < 4; i++) {
            make(content, `일정관리 ${i}`)
        };
        class BoxList {
            constructor(ele, title) {
                this.ele = ele
                this.title = title
                this.state = 'off'
            }
            show() {
                let data = this.state === 'on'? '데이터 사용중' : '데이터 미사용중'
                this.ele.innerHTML += `
                <div class="box ${this.state}">
                <h2>일정관리</h2>
                <p>세부 타이틀</p>
                <p>상태 : ${this.state}</p>
                <p>${data}</p>
                </div>
                `;
            }
        };
        const boxlist = new BoxList(content, 'toDo');
        boxlist.state = 'off'
        boxlist.show();
    </script>
</body>

 

class를 사용해서 html내용도 채워 넣었다.

state 상태변호를 사용해 on / off 일 때 다른 값이 출력되도록 했다.

 

 

 

2) class 연습 예제 #2

 

const get = (target) => {
    return document.querySelector(target)
}
const getAll = (target) => {
    return document.querySelectorAll(target)
}

const $slides = getAll('.slide')
const $next = get('.next')
const $prev = get('.prev')

class Banner {
    interval = 1000
    timer = null
    auto = true
    constructor() {
    }
    init() {
        if (this.auto) this.timer = setInterval(this.nextSlide, this.interval)
        $next.addEventListener('click', e => {
            this.nextSlide();
            if (this.auto) {
                clearInterval(this.timer);
                this.timer = setInterval(this.nextSlide, this.interval)
            }
        })
        $prev.addEventListener('click', e => {
            this.prevSlide();
            clearInterval(this.timer);
            this.timer = setInterval(this.prevSlide, this.interval)
        })
    }
    nextSlide() {
        const current = document.querySelector('.current');
        current.classList.remove('current');
        if (current.nextElementSibling) current.nextElementSibling.classList.add('current');
        else $slides[0].classList.add('current');
    }
    prevSlide() {
        const current = document.querySelector('.current');
        current.classList.remove('current');
        if (current.previousElementSibling) current.previousElementSibling.classList.add('current');
        else $slides[$slides.length - 1].classList.add('current');
    }
}

const banner = new Banner()
banner.init()
    <div class="banner">
        <div class="slide current">
            <div class="box">
                <h2>배너 타이틀 1</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore nemo natus architecto placeat eos
                    consequuntur autem. Obcaecati illum eligendi nisi quam, facere repellat impedit, odit et dolores
                    dolorum vero asperiores?</p>
            </div>
        </div>
        <div class="slide">
            <div class="box">
                <h2>배너 타이틀 2</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore nemo natus architecto placeat eos
                    consequuntur autem. Obcaecati illum eligendi nisi quam, facere repellat impedit, odit et dolores
                    dolorum vero asperiores?</p>
            </div>
        </div>
        <div class="slide">
            <div class="box">
                <h2>배너 타이틀 3</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore nemo natus architecto placeat eos
                    consequuntur autem. Obcaecati illum eligendi nisi quam, facere repellat impedit, odit et dolores
                    dolorum vero asperiores?</p>
            </div>
        </div>
        <div class="slide">
            <div class="box">
                <h2>배너 타이틀 4</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore nemo natus architecto placeat eos
                    consequuntur autem. Obcaecati illum eligendi nisi quam, facere repellat impedit, odit et dolores
                    dolorum vero asperiores?</p>
            </div>
        </div>
        <div class="slide">
            <div class="box">
                <h2>배너 타이틀 5</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore nemo natus architecto placeat eos
                    consequuntur autem. Obcaecati illum eligendi nisi quam, facere repellat impedit, odit et dolores
                    dolorum vero asperiores?</p>
            </div>
        </div>
        <div class="slide">
            <div class="box">
                <h2>배너 타이틀 6</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore nemo natus architecto placeat eos
                    consequuntur autem. Obcaecati illum eligendi nisi quam, facere repellat impedit, odit et dolores
                    dolorum vero asperiores?</p>
            </div>
        </div>
    </div>

 

위 코드처럼 html에 직접 작성 된 내용에 class를 적용 할 수도 있고, 아래 코드처럼 스크립트에 배열로 추가해 구현할 수도 있다.

 

const get = (target) => {
    return document.querySelector(target)
}
const getAll = (target) => {
    return document.querySelectorAll(target)
}

const $slides = getAll('.slide')
const $boxs = getAll('.slide .box')
const $next = get('.next')
const $prev = get('.prev')

class Banner {
    interval = 1000
    timer = null
    auto = true
    constructor(data) {
        this.data = data
    }
    init() {
        if (this.auto) this.timer = setInterval(this.nextSlide, this.interval)
        $next.addEventListener('click', e => {
            this.nextSlide();
            if (this.auto) {
                clearInterval(this.timer);
                this.timer = setInterval(this.nextSlide, this.interval)
            }
        })
        $prev.addEventListener('click', e => {
            this.prevSlide();
            clearInterval(this.timer);
            this.timer = setInterval(this.prevSlide, this.interval)
        })
    }
    nextSlide() {
        const current = document.querySelector('.current');
        current.classList.remove('current');
        if (current.nextElementSibling) current.nextElementSibling.classList.add('current');
        else $slides[0].classList.add('current');
    }
    prevSlide() {
        const current = document.querySelector('.current');
        current.classList.remove('current');
        if (current.previousElementSibling) current.previousElementSibling.classList.add('current');
        else $slides[$slides.length - 1].classList.add('current');
    }
    show(){
        for(let i=0; i<data.length; i++){
            $slides[i].children[0].innerHTML=`
            <h2>${data[i].title}</h2>
            <p>${data[i].des}</p>
            `
        }
    }
}
const data = [
    {id : 1, title : '월요일', des:'기쁘며, 위하여 못하다 눈이 스며들어 속에 부패뿐이다. 인간은 힘차게 같으며, 이것을 고동을 사랑의 되는 모래뿐일 있으며, 이것이다'},
    {id : 2, title : '화요일', des:'하는 같은 인생을 들어 작고 힘있다. 얼마나 밥을 인간이 더운지라 이성은 부패뿐이다. 끓는 얼마나 우리의 뜨고, 인간에 하는 사막이다'},
    {id : 3, title : '수요일', des:'오직 피가 들어 열락의 되려니와, 황금시대다. 무엇이 새가 얼음에 시들어 오직 설산에서 인도하겠다는 칼이다. 얼마나 천고에 가치를 생생하며, 밝은 아름다우냐?'},
    {id : 4, title : '목요일', des:'봄바람을 대고, 이 기관과 못할 그들의 이상의 심장은 때문이다. 노래하며 이상을 하는 생생하며, 일월과 예수는 장식하는 긴지라 아름다우냐?'},
    {id : 5, title : '금요일', des:'슬퍼하는 사람들의 별들을 오는 거외다. 못 벌써 흙으로 라이너 토끼, 가득 이런 버리었습니다.'},
    {id : 6, title : '토요일', des:'못 이름자를 하나에 많은 듯합니다. 오면 청춘이 사랑과 버리었습니다. 무성할 하나 별 마디씩 부끄러운 이국 까닭입니다.'}
]
const banner = new Banner(data)
banner.init()
banner.show()

 

'🔥 부트캠프-웹 개발 🔥/JavaScript_advanced' 카테고리의 다른 글
  • [DAY - 59] async / await, fetch, axios, insertAdjacentHTML, 데이터 출력 예제
  • [DAY - 58] static, private, try / catch
  • [DAY - 56] extends, instanceof, overriding, 메서드 추가 / 재정의, overloading, getter / setter
  • [DAY - 55] JSON, 구조분해, 생성자 함수, class
Yeonhub
Yeonhub
✨ https://github.com/yeonhub 📧 lsy3237@gmail.com
  • Yeonhub
    비 전공자의 Be developer
    Yeonhub
  • 전체
    오늘
    어제
    • 전체보기 (169)
      • 🔍 Tech 🔍 (19)
        • Front-End (11)
        • Back-End (4)
        • AI (1)
        • Server (1)
        • Etc (2)
      • 💡 원티드 프리온보딩 챌린지 💡 (14)
        • PRE-ONBOARDING_AI (11월) (1)
        • PRE-ONBOARDING_FE (2월) (2)
        • PRE-ONBOARDING_FE (1월) (2)
        • PRE-ONBOARDING_FE (12월) (9)
      • 🔥 부트캠프-웹 개발 🔥 (118)
        • HTML5 (7)
        • CSS3 (21)
        • JavaScript (27)
        • JavaScript_advanced (9)
        • React (24)
        • Next (1)
        • MYSql (5)
        • Node (5)
        • 오늘하날(개인프로젝트) (12)
        • 이젠제주투어(팀프로젝트) (7)
      • 💻 CS 💻 (1)
        • 알고리즘 (1)
      • ⚡ 코딩테스트 ⚡ (11)
        • JavaScript (11)
      • 📚 Books 📚 (6)
        • 클린 아키텍처 (2)
        • 인사이드 자바스크립트 (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    expo 지도
    Node
    expo admob
    node.js fcm
    node fcm
    react native analytics
    expo fcm push
    node cron
    라스콘4
    bottom sheet
    프론트엔드 테스트코드
    node crontab
    react vite
    react native expo fcm
    라스콘
    expo deep linking
    컴파운드 컴포넌트 패턴
    react native firebase analytics
    react native bottom sheet
    react native admob
    python node
    rn bottom sheet
    expo node fcm
    expo google map
    expo fcm
    php node
    expo map
    javascript fcm
    rn admob
    expo 길찾기
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Yeonhub
[DAY - 57] class 예제 연습
상단으로

티스토리툴바