---
title: "toggleClass()"
author: "jackroomage"
date: "2013-07-02T12:07:00Z"
tags: []
categories: ["Web前端"]
slug: "toggleclass"
draft: false
lastmod: "2013-07-02T12:08:51Z"
id: 1897342
url: "https://jackroomage.iteye.com/blog/1897342"
---

# toggleClass()

 

 

`<!DOCTYPE html>`

`<html>`

`<head>`

`<style>`

 

`p { margin: 4px; font-size:16px; font-weight:bolder;`

`cursor:pointer; }`

`.blue { color:blue; }`

`.highlight { background:yellow; }`

`</style>`

`<script src="http://code.jquery.com/jquery-1.9.1.js"></script>`

`</head>`

`<body>`

`<p class="blue">Click to toggle</p>`

`<p class="blue highlight">highlight</p>`

`<p class="blue">on these</p>`

`<p class="blue">paragraphs</p>`

`<script>`

`$("p").click(function () {`

`$(this).toggleClass("highlight");`

`});`

`</script>`

 

`</body>`

`</html>`

 

\~~~~~~~~~~~~~~~~~~~~  简单的说明一下：

class的值不是替换：而是在后面追加赋值。

 

 

例子2、

&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;  
&lt;html&gt;  
 &lt;head&gt;  
  &lt;title&gt; New Document &lt;/title&gt;  
      &lt;script src="c:\\jquery.js"&gt;&lt;/script&gt;  
 &lt;/head&gt;  
    &lt;script&gt;  
    $(function(){  
         $("input").bind("mouseover  mouseout",function(){

            $(this).toggleClass("over");  
           alert($("input").attr("class"));

         });  
         });  
    &lt;/script&gt;  
 &lt;body&gt;  
          &lt;input class="inputclass" type="button" value="测试"&gt;&lt;/input&gt;

 &lt;/body&gt;  
&lt;/html&gt;