모두와 나누는 웹개발 노트

share and care with love.

CSS & HTML & JavaScript

[JS] Javascript로 placeholder 대신하기

mere hope 2011. 7. 4. 17:34
placeholder는 input 폼에 글자가 입력되기 전 기본으로 보여주는 텍스트이다.
 
예를들면,

이렇게 입력하면 아래 스크린샷 같은 결과가 출력된다.

type 속성이 password 일지라도 위와 같이 텍스트가 출력되는 등,
미리 지시사항 등을 등록해놓을 수 있기 때문에 공간절약에 탁월한 장점이 있으나... 문제는, 역시나 Internet Explorer는 전혀 인식하지 못한다는 것.
아래와 같은 자바스크립트를 이용하면 placeholder 태그와 같은 효과를 낼 수 있다.

// Placeholder for IE function activatePlaceholders() { var detect = navigator.userAgent.toLowerCase();  if (detect.indexOf("safari") &gt; 0) return false; var inputs = document.getElementsByTagName("input"); for (var i=0;i<inputs.length;i++) {="" if="" (inputs[i].getattribute("type" "text"="" ||="" inputs[i].getattribute("type" "password")="" (inputs[i].getattribute("placeholder" &&="" inputs[i].getattribute("placeholder"> 0) {     inputs[i].value = inputs[i].getAttribute("placeholder"); 	inputs[i].style.color = '#cccccc';     inputs[i].onfocus = function() {      if (this.value == this.getAttribute("placeholder")) {       this.value = ""; 	  this.style.color = "#000000";      }      return false;     }     inputs[i].onclick = function() {      if (this.value == this.getAttribute("placeholder")) {       this.value = ""; 	  this.style.color = "#000000";      }      return false;     }     inputs[i].onblur = function() {      if (this.value.length &lt; 1) {       this.value = this.getAttribute("placeholder"); 	  this.style.color = '#cccccc';      }     }    }   } } } window.onload=function() { activatePlaceholders(); }</inputs.length;i++)>

본 스크립트는 기존에 입력값이 있을 경우에도 초기화시켜버리는 단점이 있으므로 살짝 수정이 필요하다.



 

반응형
LIST