728x90
    
    
  [Front-end / Javascript] 프론트엔드 자바스크립트로 좌표 값 구하기

브라우저에서 좌표값은 크게 두가지 종류로 나뉘는데
첫번째는 "전체 스크롤 기준" 으로 구할 수 있고
두번째는 "현재 창 기준"으로 구할수 있다
기본 형태
//브라우저 전체 (스크롤 전체) 기준 좌표 값
event.pageX : 스크롤 전체 기준 X 좌표 값
event.pageY : 스크롤 전체 기준 Y 좌표 값
//현재 창 기준 좌표 값
event.clientX : 현재 창 기준 X 좌표 값
event.clientY : 현재 창 기준 Y 좌표 값
아래 예제는 클릭했을때
현재 포인터가 위치한 좌표를 구하는 예제이다
샘플 예제
<!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>좌표 값 구하기 예제</title>
    <style>
        body {
            height: 300vh;
        }
        .items {
            display : flex;
            flex-direction: column;
            align-items: center;
            background-color: lightsteelblue;
            width : 260px;
        }
        .item {
            width : 250px;
            height:250px;
            background-color : lightgoldenrodyellow;
            margin : 3px;
        }
    </style>
</head>
<body>
    <div class="items">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
    <!-- Chapter : 좌표 [브라우저 기준 / 현재 화면 기준]-->
    <script>
        let browserPoint = (event)=>{
            console.log(`브라우저 좌표 : (${event.pageX}, ${event.pageY})`);
        }
        let clientPoint = (event) =>{
            console.log(`화면 좌표 : (${event.clientX}, ${event.clientY})`);
        }
        window.addEventListener('click',e=>{
            browserPoint(e);
            clientPoint(e);
        });
    </script>
</body>
</html>
출력 결과

728x90
    
    
  '프론트엔드 > Javascript' 카테고리의 다른 글
| [Javascript] script 태그 안에 defer란? (0) | 2021.05.21 | 
|---|---|
| [FrontEnd / Javascript] 스크롤 이동 ScrollBy ScrollTo (0) | 2021.05.21 | 
| [프론트엔드 / 자바스크립트] 브라우저 엘리먼트 좌표 값 구하기 elem.getBoundingClientRect() (0) | 2021.05.20 | 
| [프론트엔드] 윈도우 창 / 스크롤바 / 브라우저 사이즈 feat 자바스크립트 (0) | 2021.05.20 | 
| [Javascript] 페이스북 아이디로 간편 로그인 기능 구현 Facebook Login (2) | 2021.05.14 | 
										
									
										
									
										
									
										
									
댓글