jquery文本框获得焦点,jquery文本框失去焦点

发布时间:2020-02-04编辑:脚本学堂
jquery文本框焦点事件的例子,jQuery文本框获得焦点,jquery文本框失去焦点的方法示例,失去焦点,如果文本框中为空,也就是没有输入内容,就将值还设为默认值。

一、jquery文本框取得焦点
css代码:
 

.focus {
 border: 1px solid #f00;
 background: #fcc;
}
 

当焦点获得时,添加focus样式,添加边框,并改背景色为#fcc。

html代码:
 

<body>
<form action="" method="post" id="regForm">
<fieldset>
<legend>个人基本信息</legend>
<div>
<label  for="username">名称:</label>
<input id="username" type="text" />
</div>
<div>
<label for="pass">密码:</label>
<input id="pass" type="password" />
</div>
<div>
<label for="msg">详细信息:</label>
<textarea id="msg" rows="2" cols="20"></textarea>
</div>
</fieldset>
</form>
</body>
 

这里有两个input,一个textare框。
:input匹配 所有 input, textarea, select 和 button 元素。

jquery事件代码:
 

<script type="text/javascript">
$(function(){
$(":input").focus(function(){
  $(this).addClass("focus");
}).blur(function(){
  $(this).removeClass("focus");
});
})
</script>

用:input匹配所有的input元素,当获取焦点时,就添加样式focus,通过$(this)自动识别当前的元素。
focus()方法是获取焦点事件发生时执行的函数。blur()方法是失去焦点事件发生时执行的函数。

二、jquery文本框焦点事件的例子

文本框里有默认的内容,作为提示信息,获取焦点后,要让它消失。

改造:
 

复制代码 代码示例:
<script type="text/javascript">
$(function(){
$(":input").focus(function(){
  $(this).addClass("focus");
  if($(this).val() ==this.defaultValue){ 
  $(this).val("");  
  }
}).blur(function(){
 $(this).removeClass("focus");
 if ($(this).val() == '') {
$(this).val(this.defaultValue);
 }
});
})
</script>

做个逻辑判断,如果值为默认值,就将文本框中的内容清空。

失去焦点,如果文本框中为空,也就是没有输入内容,就将值还设为默认值。

jquery 文本框赋值是利用了id来取,然后利用了val来设置对应文本输入框的值哦,还就是jquery定义增加css属性就是用$("#borough_addr_tr").css("display",""); 来实例。
<!--
jquery 文本框赋值是利用了id来取,然后利用了val来设置对应文本输入框的值哦,还就是jquery定义增加css教程属性就是用
$("#borough_addr_tr").css("display",""); 来实例。
 

复制代码 代码示例:
<!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>jquery 文本框赋值</title>
<script language="网页特效">
function addtoboroughitem(bid,bname,b_addr){
 $("#borough_id").val(bid);
 $("#borough_name").val(bname);
 $("#borough_addr").val(b_addr);
 $("#borough_addr_tr").css("display","");
}
</script>
</head>
<body>
<div id="borough_addr_tr">
<input id="borough_id" type="input" />
<input id="borough_name" type="input" />
<input id="borough_addr" type="input" />
</div>
</body>
</html>