跳转至

Jquery 操作类

write by 2019/6/14 23:33

1. 介绍

jQuery 拥有若干进行 CSS 操作的方法。我们将学习下面这些:

  • addClass() - 向被选元素添加一个或多个类
  • removeClass() - 从被选元素删除一个或多个类
  • toggleClass() - 对被选元素进行添加/删除类的切换操作
  • css() - 设置或返回样式属性

样式实例

<style type="text/css">
    #div1 {
        background-color: red;
        width: 100px;
        height: 150px;
    }

    #div2 {
        background-color: yellow;
        width: 100px;
        height: 150px;
    }
</style>

2. 案例

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>caimengzhi blog jquery</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <style type="text/css">
        .red {
            color: red;
        }

        .blue {
            color: #6cff31;
        }

        .deeppink {
            color: deeppink;
        }
    </style>
</head>
<body>
<div id="div1">
    <h3>hello python</h3>
    <h4 class="blue">hello vue</h4>
    <b>hello jquery</b>
</div>
<button id="btn1">addClass</button>
<button id="btn2">removeClass</button>
<button id="btn3">toggleClass</button>
</body>
<script>
    $(function () {
        $('#btn1').click(function () {
            $('h3').addClass("red")
        });
        $('#btn2').click(function () {
            $('h4').removeClass("blue")
        });
        $('#btn3').click(function () {
            $('b').toggleClass('deeppink')
        });
    })
</script>
</html>
操作类