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

JavaScript - CSS 좌표값(clientX / Y)

쎈코 2023. 5. 7. 23:47

<!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: 0px;
            top: 0px;
        }

    </style>
</head>
<body>
    
    <div id="box1" class="box bg-red">상자1</div>
    <div id="box2" class="box bg-orange">상자2</div>
    <div id="box3" class="box bg-yellow">상자3</div>
    <div id="box4" class="box bg-blue">상자4</div>
    <div id="box5" class="box bg-green">상자5</div>

    <script>

        const box1 = document.getElementById('box1');
        const list = document.getElementsByClassName('box');
        let index = 0;
        let zindex = 1;

        window.onmousedown = function() {
            clientX/Y: 문서의 좌측 상단을 꼭짓점으로 둠
            alert( `${event.clientX}:${event.clientY}` );

            커서로 클릭하는 곳이 box1의 left값이 됨
            box1.style.left = event.clientX + 'px';
            box1.style.top = event.clientY + 'px';

            list[index].style.left = event.clientX + 'px';
            list[index].style.top = event.clientY + 'px';

            커서 누르는 곳이 상자의 가운데이도록 이동 > 상자 크기의 반만큼씩 이동시킴
            list[index].style.left = event.clientX - 100 + 'px';
            list[index].style.top = event.clientY - 100 + 'px';
            list[index].style.zIndex = zindex;  //zIndex : 앞으로 튀어나오는 것

            index++;
            zindex++;

            if (index >= list.length) index = 0;

        };

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