[英]Text in HTML Field to disappear when clicked?
我可以輕松地創建一個已包含文本的html輸入字段。 但是當用戶點擊輸入字段時,文本不會消失但會保留在那里。 然后,用戶必須手動刪除要鍵入的文本。 如何創建輸入字段,當用戶單擊輸入字段框時,文本會消失?
您要做的是使用HTML5屬性placeholder
,它允許您為輸入框設置默認值:
<input type="text" name="inputBox" placeholder="enter your text here">
這應該達到你想要的。 但是,請注意,因為Internet Explorer 9和早期版本不支持占位符屬性。
要實現這一點,您可以使用onfocus和onblur這兩個事件:
<input type="text" name="theName" value="DefaultValue"
onblur="if(this.value==''){ this.value='DefaultValue'; this.style.color='#BBB';}"
onfocus="if(this.value=='DefaultValue'){ this.value=''; this.style.color='#000';}"
style="color:#BBB;" />
這很簡單,我認為應該解決所有問題的解決方案:
<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">
這是您的提交按鈕:
<input type="submit" id= "submitBtn" value="Submit">
然后把這個小jQuery放在一個js文件中:
//this will submit only if the value is not default
$("#submitBtn").click(function () {
if ($("#valueText").val() === "ENTER VALUE")
{
alert("please insert a valid value");
return false;
}
});
//this will put default value if the field is empty
$("#valueText").blur(function () {
if(this.value == ''){
this.value = 'ENTER VALUE';
}
});
//this will empty the field is the value is the default one
$("#valueText").focus(function () {
if (this.value == 'ENTER VALUE') {
this.value = '';
}
});
它也適用於舊版瀏覽器。 此外,如果您需要,它可以很容易地轉換為普通的JavaScript。
試一試。
<label for="user">user</label>
<input type="text" name="user"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue"
value="username" maxlength="19" />
希望這可以幫助。
這很簡單: <input type="text" name="email" value="e-mail..." onFocus="this.value=''">
這樣的事怎么樣?
<input name="myvalue" type="text" onfocus="if(this.value=='enter value')this.value='';" onblur="if(this.value=='')this.value='enter value';">
這將在第一次聚焦時清除,但在用戶輸入其值后不會清除后續焦點,當留空時它將恢復給定值。
使用占位符屬性。 用戶開始輸入時文本消失。 這是我正在研究的項目的一個例子:
<div class="" id="search-form">
<input type="text" name="" value="" class="form-control" placeholder="Search..." >
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.