JS Implementation code:
The code is as follows |
Copy Code |
<input type= "text" value= "is not recommended for this" onfocus= "if (this.value = ' do not recommend doing so ') This.value = '" onblur= "if (this.value = =") thi S.value = ' Do not recommend this '/> |
I'm very opposed to writing JavaScript in HTML tags, which is the same as style written in HTML tags, although it does not violate the standards of the consortium, but it is not recommended. Because:
1, there is no reusability can be said, if it is a form, a lot of input boxes, each need such an effect, then each of these processing it?
2, if you want to modify the hint text, time-consuming and laborious and difficult to maintain.
3, we advocate the structure (HTML), performance (CSS), behavior (JavaScript) separation of the three, this is a good page.
Then how to write to achieve this effect, and both reusability, and good maintenance, and do not need to write JS into the HTML?
Believe we all have loaded jquery, I wrote a method based on jquery, first look at the DEMO, the specific methods are as follows:
1, HTML part:
The code is as follows |
Copy Code |
<input type= "text" id= "input_test" value= "input hint test"/> |
2, the introduction of JQuery:
<script type= "Text/javascript" src= "Jquery.min.js" ></script>
3. Execute script:
The code is as follows |
Copy Code |
$ (function () { var Inputel = $ (' #input_test '), Defval = Inputel.val (); Inputel.bind ({ Focus:function () { var _this = $ (this); if (_this.val () = = Defval) { _this.val ("); } }, Blur:function () { var _this = $ (this); if (_this.val () = = "") { _this.val (Defval); } } }); }) |
The final effect is the same, perhaps my personal code neat, but I believe that good code from the details start
The code is as follows |
Copy Code |
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" > <meta http-equiv= "Content-type" content= "text/html; charsetGB2312 "/> <title> text box clicks when text disappears, text appears when lost focus </title>
<body> <input type= "text" value= "Please enter your name" id= "Myinput"/> </body> <script language= "JavaScript" type= "Text/javascript" > function AddListener (ELEMENT,E,FN) { if (Element.addeventlistener) { Element.addeventlistener (E,fn,false); } else { Element.attachevent ("on" + E,FN); } } var myinput = document.getElementById ("Myinput"); AddListener (Myinput, "click", Function () { Myinput.value = ""; }) AddListener (Myinput, "blur", function () { Myinput.value = "Please enter your name"; }) </script> |