[HTML | CSS | JavaScript | jQuery] 정리/JavaScript

JavaScript - CSS 좌표값(offsetX / Y)

쎈코 2023. 5. 7. 23:54

<!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>Document</title>
    <link rel="stylesheet" href="css/example.css">
    <style>
        #box {
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
    
    <h1>Drag & Drop</h1>

    <div id="box" class="box bg-yellow"></div>

    <script>

        const box = document.getElementById('box');
        let isDown = false;       <- isDown : 마우스 버튼이 눌린 상태인지 나타내는 변수
        let x = 0;
        let y = 0;

        //마우스를 누르는 시작 > 빈 곳을 누를때는 상자가 움직이지 않게 하기
        window.onmousedown = function() {

            지금 누른 곳이 상자냐? 배경이냐?
            // alert(event.target.id); //누른 곳의 id가 나옴 > 조건으로 걸기
            if (event.target.id == 'box') {
                
                isDown = true;    

                - 상자내에서 눌린 마우스 좌표
                x = event.offsetX;      
                y = event.offsetY;
            }
        };

     영역을 상자로 국한시키면 마우스의 위치가 상자의 좌측상단 모서리의 꼭짓점이 되기 떄문에 움직임이 부자연스러워짐
        // box.onmousemove = function() {
        window.onmousemove = function() {
            if (isDown) {    // #box를 누르면 isDown = true;
                box.style.left = event.clientX + 'px';      //상자 좌측 끝 - 마우스 좌표
                box.style.top = event.clientY + 'px';
            }
        };

        window.onmouseup = function() {
            isDown = false;
        };

    </script>
</body>
</html>