input失去焦点和获得焦点jquery焦点事件
input失去焦点和获得焦点jquery焦点事件
input失去焦点和获得焦点jquery焦点事件插件,
鼠标在搜索框中点击的时候里面的文字就消失了。
我们在做网站的时候经常会用到搜索框的获得焦点和失去焦点的事件,因为懒,每次都去写非常的烦,于是就一劳永逸,遇到类似情况就来调用一下就OK了
相关js代码:
<title>input失去焦点和获得焦点jquery焦点事件插件 - 懒人建站</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ //focusblur jQuery.focusblur = function(focusid) { var focusblurid = $(focusid); var defval = focusblurid.val(); focusblurid.focus(function(){ var thisval = $(this).val(); if(thisval==defval){ $(this).val(""); } }); focusblurid.blur(function(){ var thisval = $(this).val(); if(thisval==""){ $(this).val(defval); } }); }; /*下面是调用方法*/ $.focusblur("#searchkey"); }); </script> </head>
第一种: function addListener(element,e,fn){ if(element.addEventListener){ element.addEventListener(e,fn,false); } else { element.attachEvent("on" + e,fn); } } var values = document.getElementById("searchkey"); addListener(values,"click",function(){ values.value = ""; }) addListener(values,"blur",function(){ if (values.value ==''){ values.value = "请输入用户名"; } }) 第二种:(有bug,输入名称后,鼠标离开,会显示“请输入用户名”) //获得焦点 function on_focus(){ var val = document.getElementById("searchkey"); if (val.value = "请输入用户名"){ val.value = ""; }else { val.value = val.value; } } //失去焦点 function on_blur(){ var val = document.getElementById("searchkey"); val.value = "请输入用户名"; }
<body> <form action="" method="post"> <!-- <input id="searchkey" class="search" type="search" name="s" value="请输入用户名" onBlur="on_blur();" onFocus="on_focus();" />--> <input id="searchkey" class="search" type="search" name="s" value="请输入用户名" /> </form> </body> </html>
相关推荐
开心就好 2020-06-10
<table id="table" class="table table-striped table-bordered table-hover table-nowrap" width="100%&qu
牵手白首 2020-05-14
donghongbz 2020-03-04
huha 2020-10-16
TLROJE 2020-10-26
echoes 2020-08-20
nercon 2020-08-01
zhanghaibing00 2020-06-28
Aveiox 2020-06-25
henryzhihua 2020-06-21
zhoutaifeng 2020-06-17
liangzhouqu 2020-06-16
TONIYH 2020-06-11
x青年欢乐多 2020-06-06
KyrieHe 2020-06-03
bertzhang 2020-06-02
haokele 2020-05-29