admin管理员组

文章数量:1402807

On Chris Coyer's site he uses a nice little search box. I am curious to know how you get the text in the search box to disappear and reappear when you click out of the box.

Thanks to a helpful person on this forum I use the following to have the text disappear when I click in the box:

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

Also, in Safari there is a nasty border around the input field when I click inside. What is the code for getting rid of that?

Thanks!

On Chris Coyer's site he uses a nice little search box. I am curious to know how you get the text in the search box to disappear and reappear when you click out of the box.

Thanks to a helpful person on this forum I use the following to have the text disappear when I click in the box:

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

Also, in Safari there is a nasty border around the input field when I click inside. What is the code for getting rid of that?

Thanks!

Share Improve this question asked Oct 14, 2009 at 14:37 forrestforrest 11k25 gold badges74 silver badges138 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

To reset the Search text, add an onblur:

onblur="if (this.value=='') this.value='Search';"

so your input box bees:

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

also, for the Safari border, add this in your css:

input[type=text]:focus,
input[type=password]:focus {
    outline: 0 none;
}

You can get rid of static value duplication if you make use of the defaultValue property

Compare this

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

which has three instances of the statc string "Search", to this

<input type="text" value="Search" onblur="if ('' == this.value) this.value = this.defaultValue;" onfocus="if (this.defaultValue == this.value) this.value='';"/>

which has only one.

But if you really want to take this to the "next level", you could implement something like the nearly canonical labels.js. The code is really old now, having been authored in 2002 (I think), but the concept is sound and it's basic concept has since been put to good use with modern frameworks.

I do not believe you can remove the border in Safari, though open to corrections.

To get the text to appear again when you click out of the search box, you can use this:

<input onblur="if (this.value == '') this.value ='Search';" />

本文标签: javascriptSearch Box TextShow Hide FeatureStack Overflow