본문 바로가기

클라이언트/JavaScript
CSS 조작

// CSS 조작

    - 태그에 속성값 지정하기
        ~ .style.속성명 = 값;
        ~ .style[속성명] = 값;

    - 태그 속성에 적용된 현재 서식을 읽어오기
        ~ const 변수명 = window.getComputedStyle(선택자);
        ~ 변수명.getPropertyValue('속성명');

    - classList 활용하여 클래스 속성 추가 및 제거하기
        ~ const 변수명 = document.querySelector('선택자')
        ~ 변수명.classList.add('클래스명')
        ~ 변수명.classList.remove('클래스명')


<!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>
    <style>
        #box {
            background-color: gold;
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>

    <h1>JavaScript + CSS</h1>

    <input type="button" value="확인" id="btn">
    <hr>
    <div id="box" style="width: 200px">상자</div>

    <h1>텍스트</h1>
    <div id="tool">
        <input type="button" value="  +  " id="btn1">
        <input type="button" value="  -  " id="btn2">
    </div>

    <script>

        const btn = document.getElementById('btn');
        const box = document.getElementById('box');

        btn.addEventListener('click', function () {

            //JavaScript > CSS 조작

            // 모든 것을 문자열로 조작> 관리 불편 
            // box.style = 'font-size: 2rem;'

            // box.style.color = 'blue';
            // box.style['color'] = 'white';

            // box.style.backgroundColor = 'black';
            // box.style['background-color'] = 'black';

            //상자 너비 : 200px
            // box.style.width = '400px';


            //누를 때마다 조금씩 커지게(+50px)

            //자바스크립트 > CSS로 정의된 속성값을 읽어오지 못한다.
            // 단, 인라인 시트값은 읽어올 수 있다. 임베디드와 외부 스타일시트 값을 읽어오지 못한다.
            // alert(box.style.width); // 200px이 아니라 null이 나옴.. 

            box.style.width = parseInt(box.style.width) + 50 + 'px';

            //태그에 적용된 현재 서식을 읽어오는 방식
            // const list = window.getComputedStyle(box);
            // alert(list.getPropertyValue('width'));

        });

    </script>

</body>

</html>

 

<!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>
    <style>
        #box {
            background-color: gold;
            width: 200px;
            height: 200px;
        }
    </style>
</head>

<body>

    <h1>텍스트</h1>
    <div id="tool">
        <input type="button" value="  +  " id="btn1">
        <input type="button" value="  -  " id="btn2">
    </div>

    <p id="content">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quo nulla sed corrupti maxime quod animi
        exercitationem mollitia quaerat nihil delectus odit totam, sequi nam sit voluptas eveniet commodi molestias
        dolorem! Lorem ipsum dolor sit amet consectetur, adipisicing elit. Voluptates totam repudiandae hic voluptatum
        porro ea autem assumenda tenetur eos, dignissimos facere quis nemo ipsa a sapiente quo provident quae placeat!
        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Repudiandae aliquam illo id laborum libero sequi
        aspernatur eaque, qui praesentium veniam ullam eligendi repellendus in hic cumque aperiam quo assumenda quos!
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto tenetur dolorem reprehenderit harum
        consequuntur magnam. Provident similique, vero molestiae magnam facilis, atque eveniet perferendis est odit
        commodi praesentium dicta aperiam. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dicta nemo ab
        praesentium totam delectus voluptatibus exercitationem laborum enim, asperiores quod aspernatur, voluptatem sit
        ipsam? Dolor incidunt fugiat ea aspernatur? Temporibus!</p>

    <script>

        const btn1 = document.getElementById('btn1');
        const btn2 = document.getElementById('btn2');
        const content = document.getElementById('content');

        let fontSize = 16; //16px;

        btn1.addEventListener('click', function () {
            fontSize += 1;
            content.style.fontSize = fontSize + 'px';
        });

        btn2.addEventListener('click', function () {
            fontSize -= 1;
            content.style.fontSize = fontSize + 'px';
        });

    </script>

</body>

</html>

 

<!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() {
            // alert(`${event.clientX}:${event.clientY}`);

            // box1.style.left = event.clientX + 'px';
            // box1.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;

            index++;
            zindex++;

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

        };
    
    </script>

</body>
</html>

 

<!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-green', 'bg-blue', 'bg-orange'];
        let index = 0;
        
        window.onmousedown = function () {

            // console.log(event.ctrlKey);

            if (event.buttons == 1 && !event.ctrlKey) {

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

                box.classList.add(colors[index++]) //<div class="box bg-red"></div>
                if (index >= colors.length) {
                    index = 0;
                }

                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) {
                
                // alert(event.target);
                // if(event.target.nodeName == 'DIV') 
                if (event.target.classList.contains('box')) {                    
                    
                    if (confirm('delete?')) {
                        // document.body.removeChild(event.target);// 방금 삭제된 태그까지 반환
                        event.target.remove(); //반환 타입 void
                    }
                }
            }
            
        };

    </script>

</body>

</html>

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

        .draggable {
            position: relative;
            left: 0;
            top: 0;
            user-select: none;
        }
    
    </style>
</head>
<body>

    <h1 class="draggable">제목입니다~</h1>
    <div class="box bg-red draggable">상자1</div>
    <div class="box bg-yellow draggable">상자2</div>
    <div class="box bg-blue draggable">상자3</div>
    <button class="draggable">버튼</button>

    <script>

        let isDown = false;
        let x = 0, y = 0;
        let obj; //드래그 대상(누굴 드래그 해서 움직이는지)
        let zindex = 0;
        // let ox = 0, oy = 0; //정적인 상태의 객체 위치값
        let olist = [];

        const list = document.getElementsByClassName('draggable');

        for (let i=0; i<list.length; i++) {
            olist.push ({
                obj: list[i],
                x:list[i].getBoundingClientRect().left,
                y:list[i].getBoundingClientRect().top
            });
        }

        console.log(olist);

        window.onmousedown = function() {
            
            if (event.target.classList.contains('draggable')) {
                obj = event.target;
                isDown = true;
                x = event.offsetX;
                y = event.offsetY;

                ox = getLeft(obj);
                oy = getTop(obj);

                zindex++;
                obj.style.zIndex = zindex;
            }

        }
        
        function getLeft(obj) {
            for(let i=0; i<olist.length; i++) {
                if (olist[i].obj == obj) {
                    return olist[i].x;
                }
            }
        }
        
        function getTop(obj) {
            for(let i=0; i<olist.length; i++) {
                if (olist[i].obj == obj) {
                    return olist[i].y;
                }
            }
        }

        window.onmousemove = function() {

            if (isDown) {
                obj.style.left = event.clientX - x - ox + 'px';
                obj.style.top = event.clientY - y - oy + 'px';
            }

        };

        window.onmouseup = function() {
            isDown = false;
        };
        
    </script>

</body>
</html>

'클라이언트 > JavaScript' 카테고리의 다른 글

jQuery UI  (0) 2023.05.02
jQuery  (0) 2023.05.01
[자바스크립트(JavaScript)] 클로저  (0) 2023.04.27
[자바스크립트(JavaScript)] Axis  (0) 2023.04.26
[자바스크립트(JavaScript)] DOM  (0) 2023.04.26