방법 - 토글 클래스
JavaScript를 사용하여 요소에서 클래스 이름을 추가하거나 제거합니다.
버튼을 클릭하여 클래스 이름을 전환하세요!
토글 클래스
1단계) HTML 추가:
id="myDIV"를 사용하여 div 요소에 클래스 이름 추가 사이를 전환합니다(이 예에서는 버튼을 사용하여 클래스 이름을 전환합니다).
예시
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
2단계) CSS 추가:
토글할 클래스 이름 추가:
예시
.mystyle {
width: 100%;
padding:
25px;
background-color: coral;
color: white;
font-size: 25px;
}
3단계) 자바스크립트 추가:
id="myDIV"인 <div> 요소를 가져오고 "mystyle" 클래스 간에 전환합니다.
예시
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("mystyle");
}
팁: 클래스 추가 방법 도 참조하십시오 .
팁: 클래스를 제거하는 방법 도 참조하십시오 .
팁: JavaScript 참조에서 classList 속성에 대해 자세히 알아보세요 .