---
title: "jQuery 入门教程(16): 设置或取得元素的CSS class"
author: "mapdigit"
date: "2013-03-14T23:15:00Z"
tags: []
slug: "jquery-16-css-class"
draft: false
lastmod: "2013-03-22T14:03:08Z"
id: 1834147
url: "https://mapdigit.iteye.com/blog/1834147"
---

jQuery支持方法用来操作HTML元素的CSS 属性  
下面的方法为jQuery 提供的CSS操作方法：

- addClass() – 为指定的元素添加一个或多个CSS类。
- removeClass() – 为指定的元素删除一个或多个CSS类。
- toggleClass() – 为指定的元素在添加/删除CSS类之间切换。
- css() -设置或是取得CSS类型属性。

下面的StyleSheet为后面例子使用的CSS风格：

```
.important
 {
 font-weight:bold;
 font-size:xx-large;
 }

 .blue
 {
 color:blue;
 }
```

jQuery addClass示例  
下面的例子为给定的元素添加CSS风格类

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JQuery Demo</title>
    <script src="scripts/jquery-1.9.1.js"></script>

    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("h1,h2,p").addClass("blue");
                $("div").addClass("important");
            });
        });
    </script>
    <style type="text/css">
        .important
        {
            font-weight: bold;
            font-size: xx-large;
        }

        .blue
        {
            color: blue;
        }
    </style>
</head>
<body>

    <h1>Heading 1</h1>
    <h2>Heading 2</h2>
    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <div>This is some important text!</div>
    <br>
    <button>Add classes to elements</button>

</body>
</html>
```

[![20130309007](http://www.imobilebbs.com/wordpress/wp-content/uploads/2013/03/20130309007.png)](http://www.imobilebbs.com/wordpress/wp-content/uploads/2013/03/20130309007.png)  
你也可以在addClass 添加多个类的名称，如：

```
$("button").click(function(){
   $("#div1").addClass("important blue");
 }); 
```

jQuery removeClass 示例

```
$("button").click(function(){
   $("h1,h2,p").removeClass("blue");
 }); 
```

jQuery toggle()示例，下面的例子使用toggle为HTML元素在添加/删除CSS类blue之间切换

```
$("button").click(function(){
   $("h1,h2,p").toggleClass("blue");
 }); 
 
```

下一篇介绍css()的用法。