---
title: "利用jQuery实现文本框的聚焦"
author: "heartnn"
date: "2008-12-02T16:23:00Z"
tags: []
slug: "jquery"
draft: false
lastmod: "2008-12-02T16:23:00Z"
id: 288203
url: "https://heartnn.iteye.com/blog/288203"
---

作者：[Realazy](http://www.realazy.org)

先说明我们的目的。我们知道，当代浏览器（modern browsers）的文本框的聚焦(focus)样式可以通过CSS的伪类:focus来设置。假设我们有这么一段代码：

```

<form>
    <dl>
        <dt>Name: <dt>
            <dd><input type="text" /></dd>
        <dt>Password: <dt>
            <dd><input type="password" /></dd>
        <dt>Textarea: <dt>
            <dd><textarea></textarea></dd>
    </dl>
</form>
```

则我们这样的CSS就可以搞定focus样式：

```

input[type="text"]:focus, input[type="password"]:focus, textarea:focus { border: 1px solid #f00; background: #fcc; }
```

简单不过，对不？你可以拿任何一款当代浏览器来测试（Firefox, Safari, IE7）：

```

<!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" xml:lang="zh-CN">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Step 1 | jQuery Tutorial</title>
 <style type="text/css" media="screen">
  body { font: .9em/1.5 "Lucida Grande", "Trebuchet MS", "Bitstream Vera Sans", Verdana, Helvetica, sans-serif; }
  form { width: 20em; margin: 4em auto; }
  dt { clear: left; float: left; }
  dd { clear: right; margin-left: 6em; }
  input[type="text"], input[type="password"], textarea { width: 12em; border: 1px solid #ccc; }
  input[type="text"]:focus, input[type="password"]:focus, textarea:focus { border: 1px solid #f00; background: #fcc; }
 </style>
</head>
<body>
 <form>
  <dl>
   <dt>Name: <dt>
   <dd><input type="text" /></dd>
   <dt>Password: <dt>
   <dd><input type="password" /></dd>
   <dt>Textarea: <dt>
   <dd><textarea></textarea></dd>
  </dl>
 </form>
</body> 
</html>
```

IE6? 呵呵，这就是本篇教程的目的所在，没错，既然IE不支持:focus，我们只能Using DOM Scripting to Plug the Holes in CSS，不过我们用jQuery来实现。

先来看看jQuery的工作方式。jQuery使用美元符号$来返回一个jQuery对象，然后我们就可以使用jQuery提供的API（接口。很多很多很实用，赶紧参考Visual JQuery）进行操作了。

我们都不懂程序，对，我假设你跟我这样，只是了解一些最基本的语法（对不起大虾了，高手不要自扁身份）。既然我们不懂，我们就用CSS的方式来思维。

首先我们要从DOM中获得type="text", type="password"的input和textarea。对，我们伟大的美金出场了，哦，是美元符号。参考[http://proj.jquery.com/docs/Base/Expression/CSS/](http://proj.jquery.com/docs/Base/Expression/CSS/)，我们知道，我们可以这样选择到他们：

```

$("input[@type='text'], input[@type='password'], textarea")
```

选中它们以后呢？我们就要靠事件（event）来处理了。:focus对应的的事件是onfocus，然而jQuery讨厌on，于是就是focus了，多好 :) （参考[http://proj.jquery.com/docs/EventModule/](http://proj.jquery.com/docs/EventModule/)）。于是我们知道我们该这么做：

```

$("input[@type='text'], input[@type='password'], textarea").focus();
```

嘿嘿，我们已经迈出一大步了！我们要继续告诉focus该做些什么。在jQuery中，我们通常需要一些匿名函数来帮我们干些事情，不理解不打紧，让我们继续：

```

$("input[@type='text'], input[@type='password'], textarea").focus( function(){ } );
```

我们的目的是什么？对，是给聚焦的文本框加上样式。jQuery有一个css (prop)的API，参考前面的CSS，我们可以这么写：

```

css({background:"#fcc", border:"1px solid #f00"})
```

bingo! 离成功仅一步之遥。我假设你知道，返回对象自身使用this。在jQuery中，返回自身当然也是this, 但是，需要返回的对象还是jQuery对象，我们还必须使用美元符号。所以是$(this)。那么：

```

$("input[@type='text'], input[@type='password'], textarea").focus( function(){ $(this). css({background:”#fcc”, border:”1px solid #f00″})} );
```

That’s it! 然后我们该怎么执行这段代码呢？ 我们知道有一个body onload=""可以用，也知道有一个window.onload可以用，但jQuery提供了一个更佳的方案，让我们可以进一步分离结构与交互。

```

$(document).ready(function(){
    // Your code here...
});
```

所以我们只需将我们的代码放到里面去：

```

$(document).ready(function(){
    $("input[@type='text'], input[@type='password'], textarea").focus( function(){ $(this). css({background:"#fcc", border:"1px solid #f00"})} );
});
```

呵呵……貌似成功了。等等，我们要送佛送到西天，好人做到底……在上面的交互中，只有聚焦的情况，那么失焦的时候呢？嗯，我们不要想当然，失焦？那么聚焦的样式就自动清楚清除了嘛~不会的，除非我们明确告诉它。依瓢画葫芦：

```

$(this).blur(function(){$(this).css({background: "transparent", border: "1px solid #ccc"})})
```

嗯，说到jQuery的强大之处了，jQuery对象可以接受无数个函数回调/消息/方法（哪一种是正确说法，请高手指教），也就是传说中的Chainability。也就是说我们不必要分两行写，一气呵成：

```

$(document).ready(function(){
    $("input[@type='text'], input[@type='password'], textarea").focus(function(){$(this).css({background:"#fcc", border:"1px solid #f00"})}).blur(function(){$(this).css({background: “transparent”, border: “1px solid #ccc”})});
})
```

啊呵，又一次貌似完成……又等一等，我们只需要针对IE啊，其他浏览器都可以使用CSS来实现，我们何苦要用JS来降低它们的处理效率呢，所以，我们用了jQuery自带的定义：

```

$(document).ready(function(){
 if ($.browser.msie){
  $(”input[@type=’text’], input[@type=’password’], textarea”).focus(function(){$(this).css({background:”#fcc”, border:”1px solid #f00″})}).blur(function(){$(this).css({background: “transparent”, border: “1px solid #ccc”})});
 }
})
```

耶！我们真的完成了！嗯哪，要判断浏览器版本？似乎jQuery没有提供，但可以看看这个jQuery插件（plugin）：jQBrowser . 嗯嗯，似乎忘了跟大家说，jQuery还拥有许多超强的插件！有时间我整理几个出来奉献给大家。

对，看看我们这一步的成果，一定记得用IE6查看。

```

<!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" xml:lang="zh-CN">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Step 2 | jQuery Tutorial</title>
 <style type="text/css" media="screen">
  body { font: .9em/1.5 "Lucida Grande", "Trebuchet MS", "Bitstream Vera Sans", Verdana, Helvetica, sans-serif; }
  form { width: 20em; margin: 4em auto; }
  dt { clear: left; float: left; }
  dd { clear: right; margin-left: 6em; }
  input, textarea { width: 12em; border: 1px solid #ccc; }
  input:focus, textarea:focus { border: 1px solid #f00; background: #ffc; }
 </style>
 <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
 if ($.browser.msie){
  $("input[@type='text'], input[@type='password'], textarea").focus(function(){$(this).css({background:"#fcc", border:"1px solid #f00"})}).blur(function(){$(this).css({background: "transparent", border: "1px solid #ccc"})});
  }
 })
 </script>
</head>
<body>
 <form>
  <dl>
   <dt>Name: <dt>
   <dd><input type="text" /></dd>
   <dt>Password: <dt>
   <dd><input type="password" /></dd>

   <dt>Textarea: <dt>

   <dd><textarea></textarea></dd>
  </dl>
 </form>
</body> 
</html>
```

貌似又完成了一次（汗，前边不是说我们真的完成了么），不！大家看得爽的时候还记得我是做什么的吗？对对对，是Web标准！Web标准提倡什么？结构，表现，交互相分离啊，我们把样式写到了JS里边，相信这不是好事情。难不倒我们jQuery的！我们换种思路，我们把样式在一个class里定义好，在 focus的时候加上的这个class，blur的时候去掉这个class不就OK了吗？聪明……jQuery相应的API是addClass和 removeClass。过程不累赘了，否则篇幅又得增加一半（我还要睡觉，明天还要上班，可怜的上班族），代码如下：

```

$(document).ready(function(){
 if ($.browser.msie){
 $("input[@type='text'], input[@type='password'], textarea").focus(function(){$(this).addClass("ie_focus")}).blur(function(){$(this).removeClass("ie_focus")});
 }
})
```

我必须承认，我把这个class命名为ie\_focus是有点变态。嗯，进一步，虽然我们这个代码不大，但我们也分离出来一个独立文件吧。这是我们的最后步骤的演示，记得看源码哦。

```

<!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" xml:lang="zh-CN">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Step 3 | jQuery Tutorial</title>
 <style type="text/css" media="screen">
  body { font: .9em/1.5 "Lucida Grande", "Trebuchet MS", "Bitstream Vera Sans", Verdana, Helvetica, sans-serif; }
  form { width: 20em; margin: 4em auto; }
  dt { clear: left; float: left; }
  dd { clear: right; margin-left: 6em; }
  input, textarea { width: 12em; border: 1px solid #ccc; }
  input:focus, textarea:focus { border: 1px solid #f00; background: #fcc; }
  .ie_hover { background: #ffc; }
  .ie_focus { border: 1px solid #f00; background: #fcc; } 
 </style>
 <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js"></script>
 <script type="text/javascript" src="form_enhencement_for_ie.js"></script>
</head>
<body>
 <form>
  <dl>
   <dt>Name: <dt>
   <dd><input type="text" /></dd>
   <dt>Password: <dt>
   <dd><input type="password" /></dd>

   <dt>Textarea: <dt>

   <dd><textarea></textarea></dd>
  </dl>
 </form>
</body> 
</html>
```

很简单，对不？jQuery的威力不止于此，还有需多更酷更强的功能留待你我共同探索。