jquery - 在 keyDown 中删除输入中的文本
我有一个输入框,我在网站上有一些文本
<input type="text" value="Enter Name"/>
现在我需要添加,当用户开始输入某些内容(输入第一个字母)时,我的文本将消失,他将能够输入他想要的输入。
我尝试这样做:
$('#input').keypress(function () {
$(this).val("");
});
但是用户只能输入一个字母,因为它不断删除文本。
这怎么能做到呢?
谢谢
I have a input box that i have some text in site
<input type="text" value="Enter Name"/>
Now i need to add that when the user starts typing in something (enters the first letter), my text will disappear and he will be able to enter the input he wants.
I tried doing:
$('#input').keypress(function () {
$(this).val("");
});
But then the user can only enter one letter cuz it keeps on deleting the text.
How can this be done?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过使用占位符
演示来做到这一点:
http://jsfiddle.net/9VhYZ/
某些浏览器尚不支持此功能,添加后备也可以跨浏览器支持它是个好主意:
http://davidwalsh.name/html5-placeholder
更新:
你可以像这样做你要求的事情:
http://jsfiddle.net/9VhYZ/1/
You can do this by using a placeholder
Demo:
http://jsfiddle.net/9VhYZ/
Some browser doesn't yet support this, adding a fallback could also be a good idea to support it cross browser:
http://davidwalsh.name/html5-placeholder
UPDATE:
You can do what you ask for like this:
http://jsfiddle.net/9VhYZ/1/
这种技术通常被称为重影。您可以使用占位符属性加上渐进增强。通常,我喜欢通过使用类
ghostInput
并将其全局应用于页面加载来实现此目的,这样我只需通过附加全局类即可将 Ghost 属性添加到元素中。通常,您需要在输入中添加和删除另一个类,以使文本显得更亮一点,这相当容易。只需在 focus() 上将其删除并将其添加到空的 Blur() 上即可。
Often this technique is called Ghosting. You can use the placeholder attribute plus progressive enhancement. Often I like to do it by using a class
ghostInput
and having it globally applied on page load so I can add ghost properties to elements simply by appending the global class.Often with this you'll want to add and remove another class from the input to make the text appear a little bit lighter which is fairly easy. Just remove it on focus() and add it on an empty blur().
我建议使用 HTML5 的 占位符属性 而不是 JavaScript :
请注意 - 并非所有地方都支持它,但如果您可以忽略旧版浏览器,那么这绝对是可以使用的解决方案。
I would recommend using the HTML5's placeholder attribute instead of JavaScript:
Be warned - it is not supported everywhere, but if you have the luxury of ignoring older browsers then this is definitely the solution to go with.
您正在实现文本框的默认值。
您有两个选择:
placeholder="Value"
属性。并非所有浏览器都支持 HTML5,因此我会尝试两种浏览器。
You're implementing the default value of a textbox.
You have two options:
placeholder="Value"
attribute.HTML5 isn't supported by all browsers, so I'd try both.