2010-11-14 57 views

回答

1

您可以用JavaScript看看onclick事件做輸入一個值時 //想它是清楚的。這裏一個小例子:

<input type="text" onclick="this.value='';" /> 
+0

如果我想要的文字出現背部,當用戶沒有輸入文字,並點擊了框? – 2010-11-14 22:52:31

+0

這樣的事情應該工作:onblur =「this.value =(this.value =='')?'myText':this.value」onfocus =「this.value =''」value =「myText」我也認爲而不是onclick你應該使用onfocus和onblur這是其他答案的建議。 – kukudas 2010-11-15 16:46:01

3

只寫

<input type='text' name='myText' onFocus='this.value="";'/> 

更新:
如果你想值回來,如果不輸入任何

<input type="text" onfocus="if(this.value=='Search') this.value='';" onblur="if(this.value=='') this.value='Search';" value="Search" /> 
+3

您也可以使用'this.defaultValue'而不是文字。 – 2010-11-15 05:50:41

+0

@nikc Thanx提示更好的方式 – 2010-11-15 06:09:03

3

無論是上述解決方案都非常好的在線活動是不是在這種情況下很好的解決方案。您需要的是使用HTML5 placeholder屬性以及一些Javascript,爲不支持它的瀏覽器添加對它的支持。您的HTML將如下所示:

<input type="text" placeholder="Search" id="search" /> 

這將與當前版本的Safari和Chrome一起使用。對於其他瀏覽器,您可以使用此Javascript:

// Creates a new element and check if it has the 'placeholder' property 
// If it does not, then we know that the browser does not support HTML5 placeholder 
if(typeof document.createElement('input').placeholder === 'undefined'){ 
    // Find the input element with the id "search" and get the 'placeholder' attribute 
    var input = document.getElementById('search'), 
     p = input.getAttribute('placeholder'); 

    // Give it the placeholder value 
    input.value = p; 

    // Clear input on focus, then add the placeholder text 
    // back in if there's nothing there after the user changes edits the box 
    input.onfocus = function(){ 
     if(this.value === p) this.value = ''; 
    } 
    input.onblur = function(){ 
     if(!this.value) this.value = p; 
    } 
} 

你可以看到這個在這裏一個簡單的演示:http://jsfiddle.net/RT8Bf/

+0

在線示例有效,但在我的瀏覽器中不起作用,即使在在線示例中也沒有初始值,但它顯示爲'搜索',並且複製並粘貼它並且沒有'工作甚至是「搜索」這個詞都出現了。 該怎麼辦? – 2010-11-15 21:22:49

+0

@OdO你是什麼意思?你首先說它是有效的,然後它沒有。你使用的是什麼瀏覽器?當你說「沒有初始值但是它顯示爲'搜索'」時,這意味着什麼?這不是佔位符文本的要點,在輸入元素中沒有東西時顯示嗎?並停止複製和粘貼代碼 - 瞭解代碼的工作原理,然後自己使用它。 – 2010-11-16 01:45:33

+0

我的意思是,當我在這裏嘗試它: http://jsfiddle.net/RT8Bf/ 它的工作原理。 但是,當我在HTML文件中編寫代碼並嘗試在我的電腦上運行它時,它不起作用,即使單詞「搜索」未出現在框中。我的瀏覽器是Firefox的最新版本。 – 2010-11-16 06:06:59

相關問題