2011-11-17 20 views
1

請檢查下面的鏈接:如何讓輸入中有焦點的文字?

http://jsfiddle.net/cT9kg/4/

正如你可以看到它有一個按鈕搜索字段。

如果您無法理解我的意思,請查看Ask a question頁面上的「Title」輸入。

輸入有自動對焦。

我怎麼能有這麼文本已經在支持自動對焦的輸入,但只要有人類型分爲文本消失的輸入。

當有人輸入的文本輸入,但然後將其刪除,它可以追溯到它是在開始的方式:對重點用文字在它指導如何在鍵入此人輸入。

謝謝!

James

回答

0

您可以定義默認值。

焦點 - 空值,如果該值爲默認值。

當元素失去焦點時,您可以檢查它是否爲空,並且如果是 - 恢復默認值。

0

我測試過這個工作,只要確保您將<script>部分放在</body>標記之前。

<input type="text" class="input1" autofocus="focus" id="search" value="Type here..." onKeyPress="checkValue()" /> 

---- 

<script type="text/javascript"> 
    var searchEl = document.getElementById('search'); 
    var defaultValue = searchEl.value; 

    function checkValue() { 
     if (searchEl.value == defaultValue) { 
      searchEl.value = ""; 
     }   
    } 
</script> 
+0

http://jsfiddle.net/cT9kg/11/ <<我已更新jsfiddle,但它顯示藍色突出顯示的文本。我怎樣才能使它開始輸入的行在前面,當文本被刪除並且從值文本中單擊時再次出現?就像'Ask a Question'頁面上的'Title'輸入 – James

+0

不確定你的意思。試試在jsbin中:http://jsbin.com/aliziv/2/edit。 jsfiddle似乎與我的例子有問題。 –

0

你可以使用HTML placeholder屬性,但在大多數不會實現瀏覽器相當,你所追求的:只要輸入聚焦時,佔位符文本消失。

對於類似iOS的功能(也可以在Twitter等網站上找到),您需要使用JavaScript。一個例子可以是seen online here

This similar questionand this one)有一些有用的替代方案和代碼示例。

您正確使用autofocus,雖然很好,但支持各種瀏覽器。您可以添加一個JS後備,像這樣(taken from here):

<script> 
window.onload = function() { 
    if (!("autofocus" in document.createElement("input"))) { 
     document.getElementById("s").focus(); 
    } 
} 
</script> 
+0

查看我的編輯上面提供了一個簡單的方法來提供自動對焦回退。如果您打算使用許多HTML5功能,您可能需要考慮使用優秀的http://www.modernizr.com/。 – CherryFlavourPez

0

哇。我試着在Ask a question頁面的源代碼中進行挖掘。談論複雜的。

這裏是CSS File。 雖然看起來相關的位是這樣的,但它們看起來並不比格式更多(除了edit-field-overlay這個技巧。

.form-item {padding:10px 0px 15px 0px;} 
.ask-title   {margin-bottom:-15px;margin-top:-10px;} 
.ask-title-table  {width:668px;} 
.ask-title-field  {width:610px;} 
.ask-title-cell-value {padding-left:5px;} 
.edit-field-overlay {display:none;} 

HTML(TD的一些標籤移除):

<div class="form-item ask-title"> 
     <table class="ask-title-table"> 
      <tr> 
       <td class="ask-title-cell-value"> 
        <input id="title" name="title" type="text" maxlength="300" tabindex="100" class="ask-title-field" value="">       
        <span class="edit-field-overlay">what&#39;s your programming question? be specific.</span> 
       </td> 
      </tr> 
     </table> 
    </div> 

但我完全無法弄清楚相關Javascript bits.由於有這種形式,我可以看到,唯一的參考NO的onEvent處理程序該字段(title)將位於prepareEditor函數中。

有人試圖向相對新手解釋一下嗎?