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

JavaScript - CSS 조작 (with ctrl키)

쎈코 2023. 5. 7. 23:51

<!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>

    <script>

        const colors = [ 'bg-red', 'bg-yellow', 'bg-blue', 'bg-orange', 'bg-green' ];
        //색깔 배열을 넣어줌

        let index = 0;  //index 초기화


        화면 클릭 시 상자 생성 > 이동
        window.onmousedown = function() {

            console.log(event.ctrlKey); //ctrlKey : ctrl키를 눌렀는지 아닌지 앎

            if (event.buttons == 1 && !event.ctrlKey) {    //1번 버튼을 누르면서 ctrl키를 안눌렀을 때
                //ctrl키 누르면서 클릭하면 상자가 안생김

                //<div class="box"></div>
                let box = document.createElement('div');    //<div></div>

                box.classList.add('box');         //<div class="box"></div>
                // box.classList.add('bg-red'); //<div class="box bg-red"></div>
                box.classList.add(colors[index]);
                index++;   //box를 누를때마다 index 값이 1씩 증가
                if (index >= colors.length) index = 0;    //index가 배열개수를 초과하면 초기화

                box.style.left = event.clientX - 100 + 'px';
                box.style.top = event.clientY - 100 + 'px';

                document.body.appendChild(box);
            } else if (event.buttons == 1 && event.ctrlKey) {      //1번 버튼을 ctrl키와 같이 눌렀을 때

                // alert(event.target);
                if (event.target.classList.contains('box')) {

                    if (confirm('delete?')) {
                    // 컨트롤 키랑 같이 누르면 상자가 삭제됨
                    // 부모.removeChild(자식); <- 부모가 자식을 지움
                    document.body.removeChild(event.target);
                    // 스스로 삭제
                    // (=) event.target.remove();
                }

                }

            }
        };

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