When designing a form, we usually add some text prompts. For example, in the search box, we will prompt "enter a keyword ", you can hide and display the focus in a timely manner when you get the focus and lose the focus in the search box. The most common method is to set the focus using the value:
Copy codeThe Code is as follows: <form id = "search">
<Input type = "text" id = "keyword" name = "keyword" value = "enter a keyword">
<Button> Search </button>
</Form>
<Script>
Document. getElementById ("keyword"). onfocus = function (){
If (document. getElementById ("keyword"). value = "enter a keyword "){
Document. getElementById ("keyword"). value = "";
}
}
Document. getElementById ("keyword"). onblur = function (){
If (document. getElementById ("keyword"). value = ""){
Document. getElementById ("keyword"). value = "enter a keyword ";
}
}
Document. getElementById ("search"). onsubmit = function (){
Var keyword = document. getElementById ("keyword"). value;
If (keyword = "" | keyword = "enter a keyword "){
Alert ("Enter keywords ");
Return false;
}
Return true;
}
</Script>
Although such code implements the functions we need, it is not clean, because the text such as "Enter keywords" is only a prompt text, not a value, although there are no major technical problems, it is still troublesome in many cases. For example, we may make the prompt text gray and the text typed by the user black.
The following describes how to use css to achieve better results:Copy codeThe Code is as follows: <style>
# Wrapper {position: relative; display: inline ;}
# Description {position: absolute; left: 1px; color: #999999; display: none ;}
</Style>
<Form id = "search">
<Div id = "wrapper">
<Label for = "keyword" id = "description"> enter a keyword. </label>
<Input type = "text" id = "keyword" name = "keyword">
</Div>
<Button> Search </button>
</Form>
<Script>
Window. onload = function (){
If (! Document. getElementById ("keyword"). value ){
Document. getElementById ("description"). style. display = "inline ";
}
};
Document. getElementById ("keyword"). onfocus = function (){
If (! Document. getElementById ("keyword"). value ){
Document. getElementById ("description"). style. display = "none ";
}
}
Document. getElementById ("keyword"). onblur = function (){
If (! Document. getElementById ("keyword"). value ){
Document. getElementById ("description"). style. display = "inline ";
}
}
Document. getElementById ("search"). onsubmit = function (){
If (! Document. getElementById ("keyword"). value ){
Alert ("Enter keywords ");
Return false;
}
Return true;
}
</Script>
Although CSS and JS Code have more implementation methods, but the structure is more reasonable, the prompt text is displayed by introducing the label (by positioning the position attribute of CSS ), make the value itself simpler, and the prompt text and text entered by the user are easier to control in the style, such as the color depth, thus improving the form availability.