2012-03-10 26 views
1

我想獲得默認值不要離開點擊,而是當用戶開始鍵入(所以他們知道該字段是什麼)....問題是以下內容:使用jquery改變輸入內容的形式

當我使用onchange而不是onfocus時,它在開始鍵入時保留默認值。如果它把我在做的事情弄糊塗到facebook上,看看他們的搜索框是如何工作的......那就是我要做的。

<script> 

    function uFocus() { 
     $('#fakeusername').hide(); 
     $('#username').show(); 
     $('#username').focus(); 
    } 

    function uBlur() { 
     if ($('#username').attr('value') == '') { 
      $('#username').hide(); 
      $('#fakeusername').show(); 
     } 
    } 
</script> 
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:gray;' type='text' name='fakeusername' id='fakeusername' value=' Username' onfocus='uFocus()' /> 
<input style='width:202px;height:25px;margin-top:8px;font-size:14px;color:#000000;display: none' type='text' name='username' id='username' value='' onblur='uBlur()' /> 
+0

我喜歡這個想法。點擊某些東西很容易,變得分心,然後忘記你應該輸入的內容。或忘記建議的格式(電話號碼是否有破折號?)。 – DOK 2012-03-10 19:03:08

回答

2

兩個選項:

在HTML5中,placeholder屬性將模擬你想要什麼,沒有所需的JavaScript。

<input type='text' name='fakeusername' id='fakeusername' value='Username' placeholder='Type your username' /> 

第二,我相信Facebook使用的方法是將包含示例文本的背景圖像替換爲空白。因此,您可以創建兩個背景圖像(第一個包含輸入所用字體中的「輸入用戶名」字樣,第二個爲空白),並將其設置爲在輸入焦點時翻轉。

0

這是你在找什麼:

$("#fakeusername").on({ 
    focus: function() { 
     $(this).css('color', '#000'); 
    }, 
    blur: function() { 
     $(this).css('color', 'grey'); 
    }, 
    keydown: function() { 
     if ($(this).val()==' Username') { 
      $(this).val(''); 
     } 
    } 
}); 

FIDDLE

0

下面是放置標籤在輸入的頂部,並需要適當的for/ID比賽,讓瀏覽器做輸入默認的焦點,當點擊的方法在標籤上。將標籤置於輸入頂部,如果模糊上的輸入值沒有再次顯示標籤。使用標籤可以訪問

http://jsfiddle.net/UCxaZ/2