js实现输入框默认文字

来源:互联网 发布:童装淘宝店代理 编辑:程序博客网 时间:2024/06/07 20:22

没什么难的。用js和jQuery分别实现了一下。

onload=function(){var search=document.getElementById("search");// 获取对象// 文档刚刚载入时的默认样式search.value="Bing";search.style.color="gray";search.onblur=function(){// 失去焦点时if(this.value){// 输入框有值,应为黑色字体。this.style.color="";}else{// 无值时,为文档载入时样式this.value="Bing";this.style.color="gray";}};search.onfocus=function(){// 获得焦点时,清空输入框,恢复字体颜色this.value="";this.style.color="";};};


 jQuery做的。链式编程一写就很长。

$(function(){$("#search")// id选择器// 默认时.val("Bing").css("color","gray")// 获得焦点时.focus(function(){$(this).val("").css("color","")})// 将DOM对象转为jQuery对象。不转也可以,主要是为了实现编程统一。// 离开时.blur(function(){if($(this).val()){$(this).css("color","");}else{$(this).val("Bing").css("color","gray");}})});


html

<input type="text" id="search" />
原创粉丝点击