在开始写这篇文章以前,发至心里的喷下没有支持"placeholder"这个属性的浏览器,也是它们造就了这篇文章.至因而哪些浏览器,你们都心知肚明了.html
<input type="text" id="name" placeholder="用户名">
当遇到不太可爱的浏览器时,在input框里,并不会有"用户名"这3个字出现.为了让全部用户都能体验到同样的前端页面(固然只是最大化的让页面一致),咱们不得不用js来本身写个"placeholder"功能.思路以下:
前端
1:判断该用户的浏览器是否支持placeholder这个属性,若是支持,直接return;浏览器
2:用getAttribute("placeholder")获取值以后,赋值给input.value;函数
3:用onfocus事件判断input.value是否为placeholder的值,若是是,就把input.value="";(为了让用户点击后,能够直接输入,不用删除掉占位字符)spa
4:用onblur事件判断input.value是否为空,若是是就把placeholder赋值给input.vlaue;(当用户没有输入时,离开input填入占位字符)code
============================高潮来了==============================
orm
原本觉得这样写就能够了.可是没想到被type=password反杀了....htm
占位字符在type=password下.所有都是显示*****,这可不行.个人第一反应就是用setAttribute来改变type,但是呀但是.万万没想到,某个万恶的浏览器,它input的type属性是只读的,不能改变(不但不支持placeholder,type仍是只读,我只能说你厉害).事件
以后网上找了下,基本上都是建立一个新的input来替代password的,那我也只能这样诚服了,最后写成这样的函数,思路也就多一个参数,用来判断nput的type为password时,传入true,反则不用第二个参数;get
//优雅降级placeholder function placeHolder(elemId, bool) { var d = document.getElementById(elemId), text = d.getAttribute("placeholder"), newpw, ispw = bool || false; if ('placeholder' in document.createElement('input')) { return; } if (ispw) { d.style.display = "none"; newpw = document.createElement("input"); newpw.setAttribute("type", "text"); newpw.value = text; insertAfter(newpw, d); newpw.onfocus = function () { newpw.style.display = "none"; d.style.display = "inline-block"; d.focus(); }; d.onblur = function () { if (d.value == "") { newpw.style.display = "inline-block"; d.style.display = "none"; } }; } else { d.value = text; d.onfocus = function () { if (d.value == text) { d.value = ""; } }; d.onblur = function () { if (d.value == "") { d.value = text; } }; } } placeHolder("password", true); //input.type 为password时 placeHolder("name"); //input.type 为其余值时