Javascript“水印”对于文本框
我想知道如何在页面加载时将文本放入文本框中。示例:如果我有一个登录页面,我将有 2 个名为“用户名”和“密码”的文本框。当页面加载时,我希望文本框加载其中写有“用户名”的内容,因此我不必在外面放置标签。但是当用户单击文本框内部时,它应该消失。我该怎么做?
I would like to know how to put text in a textbox when the page loads. Example: If I have a login page, I would have 2 textboxes named "username" and "password". When the page loads I want the the textbox to load with "username" written inside, so I won't have to put a label for that outside. But when the user clicks inside textbox it should disppear. How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
...来自 Stack Overflow 搜索框。
您还可以添加
onblur
事件来检查:if (this.value=='') this.value = 'search'
这会在以下情况下重新打印水印:用户在文本框外部单击,该字段为空。
...from the Stack Overflow search box.
You could also add the
onblur
event to check:if (this.value=='') this.value = 'search'
This would re-print the watermark when the user clicks outside the textbox and the field is empty.
更现代的方法是使用“PlaceHolder”
A more modern way is to use "PlaceHolder"
有很多关于如何执行此操作的教程。 这是使用 jQuery JavaScript 框架的一个演练。
这是另一篇热门博客文章 关于它,只需使用常规的 javascript。
There are a lot of tutorials on how to do this. Here's one walkthrough using the jQuery javascript framework.
Here's another popular blog post about it, just using regular javascript.
通俗地说:
代码:
In laymen's terms:
The code:
JS:
在您的文本框中包含
onfocus="clearDefault(this)"
并将其文本设置为“用户名”或“密码”。JS:
In your textbox include
onfocus="clearDefault(this)"
and set its text to "username" or "password".请参阅这篇文章 http://www.alistapart.com/articles/makingcompactformsmoreaccessible。当然,如果您使用 jQuery,则有“Label over”插件。
See this article http://www.alistapart.com/articles/makingcompactformsmoreaccessible. Of course, if you are using jQuery, there are "Label over" plugins.