본문 바로가기
웹프로그래밍/JavaScript

<JavaScript>html객체의 style값 가져오기

자바스크립트를 이용해서 html 요소의 속성과 속성값을 가져올 수 있다.

특히 style속성의 속성값을 가져오는 것은 상당히 유용한데 이를 이용해서 style diplay속성값을 none으로 수정하여

html객체를 사라졌다 보였다하게 만드는 toggle(토글)기능도 구현할 수 있게 해준다.

 

아래의 예시를 통해서 버튼을 누르면 텍스트입력창이 사라지는 기능을 구현해 보겠다.

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>


<input id="inputid" type="text" name="inputtext">
<input type="button" value="버튼" onclick="toggle()">
<input id="togleid" type="hidden" name="togle" value="1">

<script type="text/javascript">

function toggle(){
	
	var ttt = document.getElementById('inputid');
	var togle = document.getElementById('togleid');
	
	if(togle.value == 1){
		ttt.style.display = "none";
		togle.value = 2;
	}else{
		ttt.style.display = "inline-block";
		togle.value = 1;	
	}
}

</script>

</body>
</html>

 

 

 

 

 

처음 실행한 화면이다.

 

 

위의 화면에서 버튼을 누르면 텍스트입력창이 사라진다.

 

다시 버튼을 누르면 텍스트입력창이 활성화가 된다

 

 

소스코드를 본다면 아마 어렵지 않게 이해가 가능하리라 생각한다.

참고로 아래의 hidden type의 input태그는 보이지가 않는다.

그래서 상태값을 저장하는 변수처럼 사용하는데 이는 개발하는 사람마음이라

hidden없이 바로 style속성값을 이용해서 if ( ttt.style.display === none ) 이런식으로 사용해도 괜찮다.

<input id="togleid" type="hidden" name="togle" value="1">

 

 

 

 

댓글