2009-12-15 50 views
7

我想知道如何在頁面加載時將文本置於文本框中。例如:如果我有一個登錄頁面,我會有兩個名爲「用戶名」和「密碼」的文本框。當頁面加載時,我希望在文本框中加載內部寫入的「用戶名」,所以我不必爲外部添加標籤。但是當用戶點擊文本框內時,它應該消失。我該怎麼做呢?用於文本框的Javascript「水印」

+0

http://stackoverflow.com/a/16471949/1257652 – 2013-05-09 22:31:19

回答

19
<input name="q" onfocus="if (this.value=='search') this.value = ''" type="text" value="search"> 

...從堆棧溢出搜索框。


您還可以添加onblur事件進行檢查:if (this.value=='') this.value = 'search'

這將重新打印水印時,文本框外的用戶點擊,字段爲空。

+2

+1簡單。 – Brandon 2009-12-15 23:50:14

+2

我也會讓文字變得更淺灰色,而不是黑色 – Faruz 2009-12-16 07:22:07

0

JS:

function clearDefault(ctl){ 
     if(ctl.value==ctl.defaultValue) { ctl.value = ""; } 
    } 

在你的文本包括onfocus="clearDefault(this)"並將其文本設置爲 「用戶名」 和 「密碼」。

+0

請勿使用'onfocus'屬性。改用事件 – 2009-12-15 23:51:48

+2

'onfocus'(以及'onblur')屬性本質上是事件。它們的值等於綁定到事件的函數的主體。所以''onfocus'的'clearDefault(this)'本質上具有這個綁定作爲你的'focus'事件處理函數。 }' – 2009-12-16 00:00:38

4

在外行人的術語:

  • 當着眼於輸入,如果值是「用戶名」,然後將其設置爲「」
  • 當從包裝盒中取出聚焦,如果該值是「」(即沒有被輸入),復位爲「用戶名」仍然提供反饋給用戶,因爲他們還沒有進入數據

代碼:

<input value="Username" onfocus="if(this.value=='Username') this.value = ''" onblur="if(this.value=='') this.value = 'Username'" type="text" /> 
5

一個更現代的方法是使用 「佔位符」

<input type="text" placeholder="search" /> 
+0

這是優雅的! – theblackpearl 2016-05-19 04:25:39