웹개발 교육/jQuery

[43일] jQuery (10) - addClass

ewok 2022. 9. 27. 11:13

addClass 함수는 하나 이상의 클래스(.)를 선택된 요소에 추가한다. 현재 요소에 적용되는 속성은 제거되지 않고 단지 속성이 추가만 된다.

$(selector).addClass(classname,function(index,currentclass))

classname은 필수사항이고, function은 선택사항이다.

 

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>10_addClass.html</title>
        <link rel="stylesheet" href="../css/reset.css"/>
        <link rel="stylesheet" href="http://fonts.googleapis.com/earlyaccess/notosanskr.css"/>
        <!-- jQuery import -->
        <script src="jquery-3.6.1.min.js"></script>
        <style>
            #box {
                width:620px;
                height:465px;
                border:1px solid #9e9e9e;
                margin:-233.5px 0 0 -310px;
                left:50%;
                top:50%;
                position: fixed;
                box-shadow: 0 12px 15px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19);
                overflow: hidden; 
            }

            #startBtn {
                width:620px;
                height:465px;
                position: absolute;
                font:700 100px "Noto Sans KR",sans-serif;
                /*1)CSS추가*/
                background-color: #66ffff;
                color: #ffffff;
                border: 0;
                cursor: pointer;
                left: 0; /*왼쪽에서부터 시작*/
                transition: .3s ease; /*부드럽게*/
            }

            /*2)CSS추가*/
            #startBtn:hover {
                background: #0033ff;
            }

            /*3)CSS추가*/
            img {
                opacity: 0;
                transform: scale(0);
                transition: .4s ease;
            }

            /*4)CSS추가*/
            #box.open #startBtn {
                left: -100%;
                transition: .4s ease;
            }

            /*5)CSS추가*/
            #box.open img {
                opacity: 1;
                transform: scale(1);
                transition: .4s ease;
            }
        </style>
    </head>  
    <body>

        <div id="box">
            <button id="startBtn">스타트!</button>
            <img src="../images/friends.jpg"/>
        </div>
        <script>
            $("#startBtn").click(function(){
                $("#box").addClass("open");
            });//click end
            
            $("img").click(function(){
                $("#box").removeClass("open");
            });//click end
        </script>
        
    </body>
</html>

addClass 함수를 통해 스타트 버튼을 클릭하면 open 클래스가 id가 box인 태그에 추가된다.

이제 이미지를 클릭하면 open 클래스가 삭제되면서 4), 5)번의 css는 없어지고 원래 적용되었던 #startBtn과 img css가 적용된다.

 

 

 

https://www.w3schools.com/JQuery/html_addclass.asp

 

jQuery addClass() Method

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com