注意:淘宝的lable是用定位制作的,事件是oninput事件
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> .wrong { border: 2px solid red; } .right { border: 2px solid #91B81D; } .lab { position: absolute; top: 56px; left: 60px; cursor: text; color: #ccc; font-size: 12px; } .show{ display:block; } .hide{ display:none; } </style> </head> <body> 京东:<input type="text" name="name" value="我是京东" id="inp1" /><br /><br /> 淘宝:<label for="inp2" id="lab" class="lab">我是淘宝</label><input type="text" name="name" value="" id="inp2" /> <script> var inp1 = document.getElementById("inp1"); var inp2 = document.getElementById("inp2"); var lab = document.getElementById("lab"); //inp1.onfocus();//页面加载完之后input标签就获取光标焦点 inp1.onfocus = function () { if (inp1.value === "我是京东") { inp1.value = ""; } } inp1.onblur = function () { if (inp1.value === "") { inp1.value = "我是京东"; } } inp2.oninput = function () { if (inp2.value === "") { lab.className = "lab show"; } else { lab.className = "lab hide"; } } </script> </body> </html>