Hide or show the text when the input box gets or loses the focus.
Input box default status:
Enter the box to get the focus status:
You can see that the search input box displays the "user name/Email" prompt by default. When the input box gets the focus, it is automatically cleared and waiting for user input, when the user leaves the input box without entering anything, the "user name/Email" prompt is displayed again in the input box. Is it common? Many searches, logins, and forms all use this effect, but I have read more than 90% of the websites:
Copy codeThe Code is as follows: <input type = "text" value = "search keyword" onfocus = "if (this. value = 'search keyword ') this. value = ''" onblur = "if (this. value = '') this. value = 'search keyword '"/>
I am very opposed to writing javascript in html tags. This is the same as writing style in html tags. Although it does not violate W3C standards, it is not recommended to write it like this. Because:
1. There is no reusability at all. If it is a form, there are many input boxes, and each of them requires such an effect, will each process it like this?
2. If you want to modify the prompt text, it is time-consuming, laborious, and difficult to maintain.
3. We advocate the separation of structure (html), presentation (css), and behavior (javascript). This is a good page.
So how can we achieve this effect through writing? It is both reusable and well maintained without writing js into html?
The specific method is as follows:
First, we must introduce jQuery.
Html code:Copy codeThe Code is as follows: <div> <input type = "text" value = "prompt test" class = "input_test"/> </div>
<Div> <input type = "text" value = "Enter the key to search" class = "input_test"/> </div>
JQuery code:Copy codeThe Code is as follows: <script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script>
<Script type = "text/javascript">
$ (Function (){
$ ('. Input_test'). bind ({
Focus: function (){
If (this. value = this. defaultValue ){
This. value = "";
}
},
Blur: function (){
If (this. value = ""){
This. value = this. defaultValue;
}
}
});
})
</Script>
You only need to add the "input_test" class in the input box to implement it easily.
View: Demo