[DAY - 32] mouse 이벤트, 상태변수, getComputedStyle, key 이벤트, 게임

2023. 4. 17. 20:11·🔥 부트캠프-웹 개발 🔥/JavaScript
  • mouse 이벤트
  • 상태변수
  • getComputedStyle
  • key 이벤트
  • 게임

 

 

1) mouse 이벤트

 

click 외에 마우스를 사용했을 때 함수가 실행되게 할 수 있다.

 

    btn.addEventListener('click', e => {
      output.innerHTML = "";
    });
    // 좌클릭
    box1.addEventListener('click', e => {
      output.innerHTML += `<div>click</div>`
    });
    // 더블클릭
    box2.addEventListener('dblclick', e => {
      output.innerHTML += `<div>dblclick</div>`
    });
    // 우클릭
    box2.addEventListener('contextmenu', e => {
      output.innerHTML +=`<div>contextmenu</div>`
    });
    // 좌클릭 했을 때
    box3.addEventListener('mousedown', e => {
      output.innerHTML += `<div>mousedown</div>`
    });
    // 좌클릭 떼었들 때
    box3.addEventListener('mouseup', e => {
      output.innerHTML += `<div>mouseup</div>`
    });
    // 마우스 안에서 움직였을 때
    box4.addEventListener('mousemove', e => {
      output.innerHTML += `<div>mousemove</div>`
    });
    // 자식 요소 감지(자식 요소에 마우스 올리면 부모 mouseout 자식 mouseover)
    box5.addEventListener('mouseover', e => {
      output.innerHTML += `<div>mouseover</div>`
    });
    box5.addEventListener('mouseout', e => {
      output.innerHTML += `<div>mouseout</div>`
    });
    // 마우스 올림/내림 
    box6.addEventListener('mouseenter', e => {
      output.innerHTML += `<div>mouseenter</div>`
    });
    box6.addEventListener('mouseleave', e => {
      output.innerHTML += `<div>mouseleave</div>`
    });

 

문법은 click과 같으며 click 자리에 무엇이 들어가는지에 따라 달라진다.

 

click : 좌클릭
dblclick : 더블클릭
contextmenu : 우클릭
mousedown : 좌클릭 했을 때
mouseup : 좌클릭 떼었을 때
mousemove : 커서를 안에서 움직였을 때
mouseover : 커서를 올렸을 때
mouseout : 커서를 내렸을 때
mouseenter : 커서를 올렸을 때
mouseleave : 커서를 내렸을 때


mouseover / mouseout는 자식에게도 상속되어 부모에 커서를 올릴 때 인식을 하고 자식에게 올렸을 때도 인식을 한다.

mouseenter / mouseleave는 부모에만 처음 반응하고 자식엔 적용되지 않는다.

 

 

 

2) 상태변수

 

<body>
    <div class="box box1"></div>
    <p>
        <button>확인</button>
    </p>
    <script>
        'use strict';
        let isColor = true;
        let btn = document.querySelector('button');
        let dom = document.querySelectorAll('.box')

        btn.addEventListener('click', e => {
            isColor ? dom.forEach(item => {
                item.style.backgroundColor = 'pink', btn.innerHTML='pink';
            }) : dom.forEach(item => {
                item.style.backgroundColor = 'yellow', btn.innerHTML='yellow';
            })
            isColor = !isColor;
        })
    </script>
</body>

 

isColor를 상태변수로 지정하고 삼항연산자를 사용하여 isColor가 true이면 dom의 backgroundColor를 pink로 바꾸고, isColor의 값을 뒤집어 준다.

그 뒤에 버튼을 누르면 isColor가 false이므로 같은 원리로 yellow가 된다.

 

 

3) getComputedStyle

 

요소의 css 속성값을 뽑아낼 때 사용한다.

 

<style>
	h2::After {
        content: 'HI';
        display: none;
  		}
        .box {
        width: 150px;
        height: 30px;
        border: 1px solid #000;
        background: tan;
        position: relative;
        left: 10px;
        top: 10px;
        margin-bottom: 50px;
        padding: 10px;
    }
</style>

    <h2>HELLO</h2>
    <div class="box">xx</div>
    <p>
        <button>BTN1</button>
        <button>BTN2</button>
        <button>BTN3</button>
        <button>BTN4</button>
    </p>
    <script>
        'use strict';
        let h2 = document.querySelector('h2');
        let dom = document.querySelector('.box');
        let btn = document.querySelectorAll('button');
        let x, y;

        btn[0].addEventListener('click', e=>{
            x = dom.style.left;
            y = dom.style.top;
            dom.textContent = `x : ${x}, y : ${y}`
        });
        btn[1].addEventListener('click', e=>{
            x = getComputedStyle(dom).left;
            y = getComputedStyle(dom).top;
            dom.textContent = `x : ${x}, y : ${y}`
        });
        btn[2].addEventListener('click', e=>{
            x = getComputedStyle(dom).width;
            y = getComputedStyle(dom).height;
            dom.textContent = `x : ${x}, y : ${y}`
        });
        btn[3].addEventListener('click', e=>{
            x = getComputedStyle(h2, ':after').content;
            dom.textContent = x;
        });
    </script>

BTN1
BTN2
BTN3
BTN4

 

btn0과 같이 dom.style을 하면 아무것도 나오지 않는다.

 

* ::After나 ::Before도 뽑아낼 수 있다.

 

 

4) key 이벤트

 

마우스와 마찬가지로 키보드 혹은 특정키를 누를 때 함수가 실행되게 할 수 있다.

 

    <script>
        'use strict';
        let dom = document.querySelector('.box');

        window.addEventListener('keydown', e=>{
            dom.textContent = e.keyCode+`=`+e.key;
        })
    </script>

 

keydown : 키보드 누를 때
keyup : 키보드 뗄 때
keypress : 키보드 누를 때(한글 X)
keyCode : 키보드의 아스키 코드값
key : 아스키 코드값을 키값으로 변경

 

키보드를 누르게 되면 아스키 코드값 = 키값이 dom에 출력된다.

 

shift
b

 

이를 응용하여 숫자키를 누르면 해당하는 사진의 크기가 커지도록 해 보았다.

 

    <script>
        'use strict';
        let li = document.querySelectorAll('li')

        window.addEventListener('keydown', e=>{
            li.forEach(item => {
                item.classList.remove('on');
            });
            li[Number(e.key)-1].classList.add('on');
        });
    </script>

 

인덱스 번호와 숫자키의 시작점이 다르므로 1을 빼 맞추었다.

 

 

 

5) 게임

 

    <script>
        'use strict';
        let pic = document.querySelector('.box img');
        let btn = document.querySelectorAll('.btn button');
        let dom = document.querySelector('.box');
        let x = parseInt(getComputedStyle(pic).left);
        let y = parseInt(getComputedStyle(pic).top);
        let w = parseInt(getComputedStyle(dom).width);
        let h = parseInt(getComputedStyle(dom).height);

        btn[0].addEventListener('click', e => {
            if (x > 0) {
                x -= 10;
                pic.style.left = x + 'px';
            }
        })
        btn[1].addEventListener('click', e => {
            if (x < w-pic.width) {
                x += 10;
                pic.style.left = x + 'px';
            }
        })
        btn[2].addEventListener('click', e => {
            if (y > 0) {
                y -= 10;
                pic.style.top = y + 'px';
            }
        })
        btn[3].addEventListener('click', e => {
            if (y < h-pic.height) {
                y += 10;
                pic.style.top = y + 'px';
            }
        })
    </script>

 

getComputedStyle로 css 값을 바꾸는 것을 이용해 간단한 게임을 만들어 보았다.

버튼을 누르면 알맞게 left, top의 값이 10씩 변하도록 했다.

 

        window.addEventListener('keydown', e=>{
            console.log( e.keyCode )
            if(e.keyCode === 37){
                x -= 10;
                pic.style.left = x + 'px';
            } else if(e.keyCode === 39){
                x += 10;
                pic.style.left = x + 'px';
            } else if(e.keyCode === 38){
                y -= 10;
                pic.style.top = y + 'px';
            } else if(e.keyCode === 40){
                y += 10;
                pic.style.top = y + 'px';
            }
        });

 

키보드로도 구현이 가능하도록 코드를 추가했다.

키보드의 방향키 아스키 코드(37, 38, 39, 40)을 버튼과 같은 방식으로 적용시켰다.

 

'🔥 부트캠프-웹 개발 🔥/JavaScript' 카테고리의 다른 글
  • [DAY - 35] 버블링 / 캡쳐링, preventDefault, node, 요소, 요소 생성 / 이동
  • [DAY - 34] export / import, 예제
  • [DAY - 31] 상태 변수, data-, className, classList
  • [DAY - 30] animate, 갤러리, 갤러리+animate, load, this, target / currentTarget
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
  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Yeonhub
[DAY - 32] mouse 이벤트, 상태변수, getComputedStyle, key 이벤트, 게임
상단으로

티스토리툴바