简体   繁体   English

从输入字段中删除文本

[英]Remove text from fields on input

How do I make the text disappear like the way some fields work here on stackoverflow once I start putting in text? 一旦开始输入文本,如何使文本消失,就像某些字段在stackoverflow上的工作方式一样? I tried out the different 'on'-actions in HTML but that didn't really do what I wanted. 我尝试了HTML中不同的“ on”操作,但这并没有真正做到我想要的。

Thanks. 谢谢。

You can do it with onfocus/onblur events. 您可以通过onfocus / onblur事件来做到这一点。 For example: 例如:

<input type="text" value="search" onfocus="if(this.value=='search')this.value=''"/>

If you click on this input field, the default text "search" will disappear. 如果单击此输入字段,则默认文本“搜索”将消失。 The onfocus event handler checks if this input field has the value of "search" and if so then clears it, in other cases (user has already typed something in) leaves everything as is. onfocus事件处理程序检查此输入字段是否具有“搜索”的值,如果是,则将其清除,在其他情况下(用户已在其中键入内容)则一切保持不变。

Presumably you mean "Labels which appear inside the input". 大概是指“标签出现在输入中”。

If you want to do this in a sane, accessible, semantic way — use a <label> , if JS is available then position it under the element, and onfocus/onblur change classes around based on the value of the element. 如果要以理智,可访问的语义方式执行此操作—使用<label> ,如果JS可用,则将其放在元素下,然后onfocus / onblur根据元素的值更改类。

I knocked up a simple example at http://dorward.me.uk/tmp/label-work/example.html using jQuery (all the source that isn't part of the jQuery library is embedded in the HTML of that document for easy reading). 我使用jQuery在http://dorward.me.uk/tmp/label-work/example.html上敲了一个简单的示例(并非jQuery库一部分的所有源代码都嵌入了该文档的HTML中,用于易于阅读)。

jQuery would make this easy work; jQuery将使这项工作变得简单。 http://www.jsfiddle.net/TshDN/ http://www.jsfiddle.net/TshDN/

If you are using HTML 5 you could use the placeholder attribute. 如果您使用的是HTML 5,则可以使用占位符属性。

http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute http://dev.w3.org/html5/spec/Overview.html#the-placeholder-attribute

在javascript中使用onFocus()

<input type="text" onfocus="if(this.value == 'value') { this.value = ''; }" value="value" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM