Zac*_*ith 35 html javascript user-interface dom-events
我可以轻松地创建一个已包含文本的html输入字段.但是当用户点击输入字段时,文本不会消失但会保留在那里.然后,用户必须手动删除要键入的文本.如何创建输入字段,当用户单击输入字段框时,文本会消失?
Nay*_*ish 153
您要做的是使用HTML5属性placeholder,它允许您为输入框设置默认值:
<input type="text" name="inputBox" placeholder="enter your text here">
这应该达到你想要的.但是,请注意,因为Internet Explorer 9和早期版本不支持占位符属性.
Bit*_*ink 21
要实现这一点,您可以使用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;" />
Run Code Online (Sandbox Code Playgroud)
使用占位符属性。当用户开始输入时,文本就会消失。这是我正在从事的一个项目的示例:
<div class="" id="search-form">
<input type="text" name="" value="" class="form-control" placeholder="Search..." >
</div>
Run Code Online (Sandbox Code Playgroud)
小智 5
试试这个。
<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" />
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
这很简单,我认为应该解决所有问题的解决方案:
<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">
Run Code Online (Sandbox Code Playgroud)
这是您的提交按钮:
<input type="submit" id= "submitBtn" value="Submit">
Run Code Online (Sandbox Code Playgroud)
然后把这个小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 = '';
}
});
Run Code Online (Sandbox Code Playgroud)
它也适用于旧版浏览器.此外,如果您需要,它可以很容易地转换为普通的JavaScript.
小智 3
像这样的事情怎么样?
<input name="myvalue" type="text" onfocus="if(this.value=='enter value')this.value='';" onblur="if(this.value=='')this.value='enter value';">
这将在第一次聚焦时清除,但在用户输入其值后不会在后续聚焦时清除,当留空时,它将恢复给定值。