首页 > 语言 > JavaScript > 正文

文本框获得焦点和失去焦点的判断代码

2024-05-06 14:22:15
字体:
来源:转载
供稿:网友
文本框失去焦点事件、获得焦点事件

onBlur:当失去输入焦点后产生该事件
onFocus:当输入获得焦点后,产生该文件
Onchange:当文字值改变时,产生该事件
Onselect:当文字加亮后,产生该文件
onpropertychange 当属性改变发生该事件
无论粘贴 keyup onchange等,最为敏感

先来看javascript的直接写在了input上

代码如下:
<input name="pwuser" type="text" id="pwuser"   class="input" value="楼盘账号"   onBlur="if(this.value=='') this.value='楼盘账号';" onFocus="if(this.value=='楼盘账号') this.value='';" />
<input name="pwpwd" type="password"    class="input1" value="******"  onBlur="if(this.value=='') this.value='******';" onFocus="if(this.value=='******') this.value='';">
 


jquery实现方法

对于元素的焦点事件,我们可以使用jQuery的焦点函数focus(),blur()。

focus():得到焦点时使用,和javascript中的onfocus使用方法相同。
如:

代码如下:
$("p").focus(); 或$("p").focus(fn)

blur():失去焦点时使用,和onblur一样。
如:

代码如下:
$("p").blur(); 或$("p").blur(fn)

实例

代码如下:
<form>
<label for="searchKey" id="lbSearch">搜神马?</label>  这里label覆盖在文本框上,可以更好的控制样式
<input id="searchKey" type="text" />
<input type="submit" value="搜索" />
 </form>
 

jquery代码

代码如下:
$(function() {
$('#searchKey').focus(function() {
$('#lbSearch').text('');
});
$('#searchKey').blur(function() {
var str = $(this).val();
str = $.trim(str);
if(str == '')
$('#lbSearch').text('搜神马?');
});
})

好了相当的不错吧

下面是一个简单的例子:

代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<script>
function tt(){
var i=document.form1.text1.value;

if(i.length>=6)
document.getElementById("s1").innerHTML="用户名不能大于6位";
else
document.getElementById("s1").innerHTML="";
}
function a(){
var j=document.form1.text2.value;
if(j.length>=6)
document.getElementById("s2").innerHTML="密码不能大于6位"
else
document.getElementById("s2").innerHTML="";
}


</script>
<body>
<form name="form1">
用户名:<input type="text" id="text1" value="请输入用户名" onfocus="javascript:document.form1.text1.value=''" onblur="tt()"/>
<span id="s1"></span><br />
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选