마우스 이벤트

치로·2024년 8월 26일

마우스 이벤트

  • 웹 브라우저는 마우스와 관련해서 다양한 이벤트 타입을 지원

1. 종류

  • click : 클릭했을 때
  • dblclick : 더블 클릭했을 때
  • mousedown : 마우스를 누를 때
  • mouseup : 마우스 버튼을 땔 때
  • mousemove : 마우스를 움직일 때
  • mouseover : 마우스가 엘리먼트에 진입할 때
  • contextmenu : 컨텍스트 메뉴가 실행될 때
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            background-color: black;
            color: white;
        }
        #target{
            width: 200px;
            height: 200px;
            background-color: green;
            margin: 10px;
        }
        
        table{
            border-collapse: collapse;
            margin: 10px;
            float: left;
            width: 200px;
        }
        td, th{
            padding: 10px;
            border: 1px solid gray;
        }
    </style>
</head>
<body>
    <div id="target"></div>
    <table>
        <tr>
            <th>event type</th>
            <th>info</th>
        </tr>
        <tr>
            <td>click</td>
            <td id="elmclick"></td>
        </tr>
        <tr>
            <td>dblclick</td>
            <td id="elmdblclick"></td>
        </tr>
        <tr>
            <td>mousedown</td>
            <td id="elmmousedown"></td>
        </tr>
        <tr>
            <td>mouseup</td>
            <td id="elmmouseup"></td>
        </tr>
        <tr>
            <td>mousemove</td>
            <td id="elmmousemove"></td>
        </tr>
        <tr>
            <td>mouseover</td>
            <td id="elmmouseover"></td>
        </tr>
        <tr>
            <td>mouseout</td>
            <td id="elmmouseout"></td>
        </tr>
        <tr>
            <td>contextmenu</td>
            <td id="elmcontextmenu"></td>
        </tr>
    </table>

    <script>
        let t = document.getElementById('target');
        
        function handler(event) {
            // console.log("--------------");
            // console.log(event.type);
            let info = document.getElementById('elm' + event.type);
            let time = new Date();
            let timestr = time.getMilliseconds();

            info.innerHTML = timestr;
        }

            t.addEventListener('click', handler);
            t.addEventListener('dblclick', handler);
            t.addEventListener('mousedown', handler);
            t.addEventListener('mouseup', handler);
            t.addEventListener('mousemove', handler);
            t.addEventListener('mouerover', handler);
            t.addEventListener('mouseout', handler);
            t.addEventListener('contextmenu', handler);
    </script>
</body>
</html>

0개의 댓글