본문 바로가기

WEB

[JavaScript] 마우스 x,y 좌표값 구하기 / client / offset / screen

마우스 x,y 좌표값 구하기

 

좌표의 종류

  1. clientX, clientY : 현재 문서 기준 위치
  2. offsetX, offsetY : 현재 오브젝트 기준 위치
  3. screenX, screenY : 현재 모니터 기준 위치

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Step02_event2.html</title>
    <style>
        .box{
            width: 500px;
            height: 500px;
            border-width:1px;
            border-style:solid;
            border-color:red;
        }
    </style>
</head>
<body>
    <div class="box" id="myDiv">div1</div>
    <script>

        document.querySelector("#myDiv").addEventListener("mousemove",function(event){
            console.log("mousemove!");
            console.log(event)
            let x = event.offsetX;
            let y = event.offsetY;
            /*
                이벤트가 일어난 좌표를
                "x 좌표:100 y좌표:200" 형식의 문자열로 만들어서
                위의 div의 innerText로 출력해보세요
            */
           document.querySelector("#myDiv").innerText = "x 좌표:"+x+"y 좌표:"+y;
        });
    </script>
</body>
</html>

function 파라미터로 event를 넣으면

이러한 오브젝트를 받을 수 있다.

event.offsetX등을 사용하면 좌표값을 얻을 수 있다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Step02_event2.html</title>
    <style>
        .box{
            width: 500px;
            height: 500px;
            border-width:1px;
            border-style:solid;
            border-color:red;
        }
    </style>
</head>
<body>
    <div class="box" id="myDiv">div1</div>
    <script>
        document.querySelector("#myDiv").addEventListener("mousedown",function(){
            document.querySelector("#myDiv").style.backgroundColor = "yellow";
        });
    </script>
</body>
</html>