본문 바로가기

Javascript

버튼 클릭했을 때 화면을 보여주거나 가리기

 

1. 스타일 속성의 기존 hide 값을 block 으로 바꾸기

 

		alertBox.setAttribute("style","display:block")

 

2. css 에 hide 클레스를 만든 후  classList에 contain() 함수를 이용하여 hide의 css를 조정

 

 

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="main.css">

</head>
<body>
	<div>
	<h2 id="title">Hello</h2>
	</div>
	<div>
			<span class="alert-box" >Alert 박스</span>
			<button id="button" onclick=button()>닫기</button>

	</div>


	




	
</body>
<script src="app.js"></script>
</html>

 

 

 

CSS

 

 

*{
	box-sizing: content-box;



}
.alert-box{

	margin-top: 100px;
	padding: 20px;
	border-radius: 4px;
	border: 2px black solid;
	text-align: center;


}
.hide{
	display: none;
}

 

JS

document.querySelector('#title').textContent="Alert버튼이 싫으면 닫기 버튼을 누르세요"
const title=document.querySelector('#title')	
const alertBox=document.querySelector('.alert-box')
const button2 =document.querySelector('#button')




//미리 디자인하고 
//버튼을 누르면 보여줌 


//만약에 버튼클릭 이벤트가 발생하면 
// class를 찾아서 속성의 값을 바꿔줘!!
function button(){
	
		if(alertBox.classList.contains('hide')){
		alertBox.classList.remove('hide')
		title.textContent="Alert버튼이 싫으면 닫기 버튼을 누르세요"
		button2.textContent="닫기"
		}else{

		alertBox.classList.add('hide')
		title.textContent="다시 보길 원하시면 열기 버튼을 누르세요"
		button2.textContent="열기"

		}

}