[드림코딩] 클릭 후 좌표 가져오기

파송송계란빡 ㅣ 2021. 9. 21. 14:45

 

getBoundingClientRect();를 이용해서 클릭한 태그의 위치 가져오기

 

Element.getBoundingClientRect()메서드는 DOMRect요소의 크기와 뷰포트에 상대적인 위치에 대한 정보를 제공 하는 객체를 반환

<!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>Coordinates</title>
    <style>
        div {
            width: 300px;
            height: 300px;
            background-color: teal;
            margin: 10px;
        }
        .special {
            background-color: tomato;
        }
    </style>
</head>
<body>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div class="special"></div>
    <div ></div>
    <div ></div>
    <div ></div>
    <div ></div>

    <script>
        const special = document.querySelector('.special');
        
        function getCoordinates(event) {
            const rect = special.getBoundingClientRect();
            console.log(rect);
            console.log(`client: ${event.clientX}, ${event.clientY}`);
            console.log(`page: ${event.pageX}, ${event.pageY}`);
        }

        special.addEventListener("click", (event) => {
            getCoordinates(event);
        });
    </script>
</body>
</html>
[드림코딩] 클릭 후 좌표 가져오기