본문 바로가기

Front end/JS (JavaScript)

자바스크립트(JavaScript) 클래스 추가, 제거 , 토글 (addClass, removeClass, toggleClass)

728x90
<script src="http://code.jquery.com/jquery-latest.min.js"></script>    
<div class="btnBox">
    <ul>
        <li class="btn1 on"><button title="">btn1</button></li>
        <li class="btn2"><button title="" ">btn2</button></li>
    </ul>
</div>

<style>
.btnBox ul li button {width:65px;height:65px;font-size: 0; margin-bottom: 15px;}
.btnBox ul li.btn1 button {background: url("//offImagePath") no-repeat; background-size: 100%;}
.btnBox ul li.btn2 button {background: url("//offImagePath") no-repeat; background-size: 100%;}

.btnBox ul li.btn1.on button {background: url("//onImagePath") no-repeat; background-size: 100%;}
.btnBox ul li.btn2.on button {background: url("//onImagePath") no-repeat; background-size: 100%;}
</style>

<script>
    $(".btnBox > ul > li").on("click", function(){
            $(this).toggleClass("on");
    })

    // or
    // $(".btnBox > ul > li").on("click", function(){
    //     if($(this).hasClass("on")){
    //         $(this).removeClass("on");
    //     }else {
    //         $(this).addClass("on");
    //     }
    // })
</script>

 

728x90