Jquery search box effect implementation method, jquery search box implementation
This article describes how to implement the jquery search box. Share it with you for your reference. The specific implementation method is as follows:
Copy codeThe Code is as follows: <Head>
<Title> jquery: search box effect </title>
<Script type = "text/javascript" src = "jquery-1.8.2.min.js"> </script>
<Script type = "text/javascript">
$ (Function (){
$ ('# Search'). val ("Enter the search content"). addClass ("c1 ");
$ ('# Search'). focus (function () {// when the search box gets the focus
$ ('# Search'). val (""). addClass ("c2 ");
});
$ ('# Search'). blur (function () {// when the search box loses focus
If ($ ('# search'). val () = ""){
$ ('# Search'). val ("Enter the search content"). attr ("class", "c1 ");
}
});
});
</Script>
<Style type = "text/css">
. C1 {color: gray; font-style: italic ;}
. C2 {color: #000; font-style: normal ;}
</Style>
</Head>
<Body>
<Input type = "text" size = "38" id = "search"/> <button> search </button>
</Body>
</Html>
Note: some are not perfect. If there are other styles in the search box, if the focus is lost and the code in the example is used, the other styles will be lost because attr () is used to set the styles. If addClass () is used as the append style, it is not very suitable. Although it can achieve the effect, the original c2 style is still in, the display is replaced by the c1 style (this requires the c1 style to be written after c2 ). Seems there is no way to replace the style?
After modification, the above problem is solved, which is a better version (the code can be optimized more easily)
Copy codeThe Code is as follows: <Head>
<Title> jquery: search box effect </title>
<Script type = "text/javascript" src = "jquery-1.8.2.min.js"> </script>
<Script type = "text/javascript">
$ (Function (){
$ ('# Search'). val ("Enter the search content"). addClass ("c1 ");
$ ('# Search'). focus (function () {// when the search box gets the focus
If ($ ('# search'). val () = "Enter the search content "){
$ ('# Search'). val (""). addClass ("c2"). removeClass ("c1 ");
}
});
$ ('# Search'). blur (function () {// when the search box loses focus
If ($ ('# search'). val () = ""){
$ ('# Search'). val ("Enter the search content"). addClass ("c1"). removeClass ("c2 ");
}
});
});
</Script>
<Style type = "text/css">
. C1 {color: gray; font-style: italic ;}
. C2 {color: #000; font-style: normal ;}
</Style>
</Head>
<Body>
<Input type = "text" size = "38" id = "search"/> <button> search </button>
</Body>
</Html>
I hope this article will help you with jQuery programming.