누르면 누른 버튼 상태가 바뀌고 또 그 상태에서 다른 버튼을 누르면 이전에 눌려있던 버튼의 생김새는 원상태로 돌아오는 기능을 구현하고 싶었뜸!!
1] 버튼 클릭시 색상 변경 및 유지
<div class="e" style="font-size:20px">창문
<button class="button" id="open" onclick="change_btn(event)">OPEN</button>
<button class="button" id="close" onclick="change_btn(event)">CLOSE</button>
</div>
이렇게 버튼 2개 구현해놓고
2] 클릭하거나 마우스를 뗀 경우에 원하는 색이 나오게 설정
.button:hover,
.button.active {
background: #7ea338;
color: white;
}
.button:visited {
background: #7ea338;
color: white;
}
.button {
border: 0;
}
3] js 구현하기
js에서 html에서으로 설정한 함수 생성
function change_btn(e) {
var btns = document.querySelectorAll(".button");
btns.forEach(function (btn, i) {
if (e.currentTarget == btn) {
btn.classList.add("active");
} else {
btn.classList.remove("active");
}
});
console.log(e.currentTarget);
}
결과

이렇게 색이 바뀜!!