2009-07-03 63 views
5

我在網上看到這一點,但想知道是否有人有最簡單的JavaScript代碼來顯示模糊輸入值,但隱藏在焦點上。如何在焦點上顯示/隱藏輸入值?

+0

咦?演出是什麼意思?你究竟想要做什麼? – 2009-07-03 05:20:21

+1

所以輸入內容會有例如「搜索...」,當你點擊輸入時,它會變成空白。我相信我已經有了答案,但是非常感謝伊恩! =] – 2009-07-03 05:57:39

回答

0

這就是我使用的my blog。只要去那裏看看背後的源代碼。

function displaySearchText(text){ 
    var searchField = document.getElementById('searchField'); 
    if(searchField != null) 
     searchField.value = text; 
} 

你輸入字段應該是這個樣子:

<input id='searchField' name='q' onblur='displaySearchText("Search...");' onfocus='displaySearchText("");' onkeydown='performSearch(e);' type='text' value='Search...'/> 
5

我所知道的最簡單的方法是:

<input 
    name="tb" 
    type="text" 
    value="some text" 
    onblur="if (this.value=='') this.value = 'some text'" 
    onfocus="if (this.value=='some text') this.value = ''" /> 
17

這總是爲我工作:

<input 
    type="text" 
    value="Name:" 
    name="visitors_name" 
    onblur="if(value=='') value = 'Name:'" 
    onfocus="if(value=='Name:') value = ''" 
/> 
7

我喜歡jQuery的方式:

$(function(){ 
    /* Hide form input values on focus*/ 
    $('input:text').each(function(){ 
     var txtval = $(this).val(); 
     $(this).focus(function(){ 
      if($(this).val() == txtval){ 
       $(this).val('') 
      } 
     }); 
     $(this).blur(function(){ 
      if($(this).val() == ""){ 
       $(this).val(txtval); 
      } 
     }); 
    }); 
}); 

它是由扎克·珀杜修改Hide Form Input Values On Focus With jQuery

17

由於這仍然出現在谷歌,我想指出,在HTML 5中,您可以使用輸入的佔位符屬性在一塊html中實現此目的。

<input type="text" id="myinput" placeholder="search..." /> 

佔位符現在是現代瀏覽器的標準,所以這真的是首選的方法。

0

對於所有瀏覽器:

<input onfocus="if(this.value == 'Your value') { this.value = '';}" onblur="if(this.value == '') { this.value = 'Your value';}" value="Your value" type="text" name="inputname" /> 

對於瀏覽器的最新版本:

<input type="text" name="inputname" placeholder="Your value" />