2013-05-04 22 views
0

我希望當我點擊任何字段時,默認文本將被隱藏,當我輸入文本時,我再次點擊相同的字段文本將不會被隱藏。隱藏字段中的默認文本 - Javascript?

我想這個代碼,但它不工作

JavaScript代碼:

for(var i = 0; i < inputs.length; i++) { 
    inputs[i].onfocus = function() { 
     if(typeof value1 != undefined) { 
      this.value = value1; 

     }else { 
      value = this.value; 
      this.value = ''; 
      this.style.color = "#000"; 
     } 
    } 

    inputs[i].onblur = function() { 
      if(this.value == '' || this.value == value) { 
       this.value = value; 
       this.style.color = "#707070"; 
      }else { 
       value1 = this.value; 
      } 
     } 
    } 
} 

回答

2

您是否在尋找placeholder屬性?如果你不想要HTML 5,你將不得不模擬當然。您將不得不添加一個類來標記輸入字段的「狀態」並對其進行測試。

<input id="fname" type="text" value="enter first name" /> 
<input id="lname" type="text" value="enter last name" /> 

$("input[type='text']").each(function() { 
    $(this).focus(function() { 
     if ($(this).hasClass("has-input")) { 
      $(this).val($(this).val()); 
     } else { 
      $(this).val(""); 
     } 
    }) 

    $(this).blur(function() { 
     if ($(this).val() !== '') { 
      $(this).addClass('has-input'); 
     } else { 
      $(this).removeClass('has-input'); 
     } 
     if (!$(this).hasClass('has-input')) { 
      $(this).val($(this).attr('value')); 
     } 
    }) 

}); 

退房小提琴:http://jsfiddle.net/djwave28/sq7V3/3/

+0

我不想使用HTML5這一次 – user2347768 2013-05-04 17:49:55

+0

爲什麼你用每個keyup強調DOM /瀏覽器? – 2013-05-04 18:49:25

+0

@莉莉絲 - 注意所做的更改。你是對的,這更優美。 – Daniel 2013-05-04 18:54:41

0

喜歡的東西:

var box=document.getElementById("text"); 
function clearTextbox(){ if(box.value==="Default")box.value=""; } 
function checkContent(){ if(box.value==="") box.value="Default" } 
box.addEventListener("focus", clearTextbox); 
box.addEventListener("blur", checkContent); 

http://jsfiddle.net/cr8dH/1/

更寬泛的版本:http://jsfiddle.net/cr8dH/5/

+0

但我想,當我在同一領域再次點擊,輸入的文本將不會被隱藏 – user2347768 2013-05-04 17:47:23

+0

我做了一個修正;) – 2013-05-04 17:48:12

+0

但我有幾個文本字段幾個默認的文本,我認爲你的代碼沒有多大幫助我 – user2347768 2013-05-04 17:57:07