Home >Web Front-end >JS Tutorial >How does jQuery dynamically add and delete CSS styles? (code example)

How does jQuery dynamically add and delete CSS styles? (code example)

青灯夜游
青灯夜游forward
2019-11-28 15:15:042483browse

How does jQuery dynamically add and delete CSS styles? (code example)

jQuery dynamically adds and removes CSS styles. There are two CSS style operation methods, one is to append the style addClass, and the other is to remove the style removeClass. The usage is explained through an example below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>jQuery动态添加删除CSS样式</title>
    <script type="text/javascript" src="http://localhost/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btn1").click(function() {
                $(&#39;#txtContent&#39;).addClass(&#39;red&#39;); //追加样式
            });
            $("#btn2").click(function() {
                $(&#39;#txtContent&#39;).removeClass(&#39;red&#39;); //移除样式
            });
            $("#btn3").click(function() {
                $(&#39;#txtContent&#39;).addClass(&#39;red weight family&#39;); //追加多个样式
            });
            $("#btn4").click(function() {
                $(&#39;#txtContent&#39;).removeClass(&#39;red weight&#39;); //移除多个样式
            });
            $("#btn5").click(function() {
                $(&#39;#txtContent&#39;).removeClass(); //移除所有样式
            });
        });
    </script>
    <style type="text/css">
        .default {
            font-size: 30px;
        }
        .red {
            color: red;
        }
        .weight {
            font-weight: bold;
        }
        .family {
            font-family: "华文隶书"
        }
    </style>
</head>
<body>
    <div id="txtContent">你好呀!jQuery基础知识!</div><br />
    <input id="btn1" type="button" value="追加样式" />
    <input id="btn2" type="button" value="移除样式" />
    <input id="btn3" type="button" value="追加多个样式" />
    <input id="btn4" type="button" value="移除多个样式" />
    <input id="btn5" type="button" value="移除所有样式" />
</body>
</html>

Recommended learning: jQuery video tutorial

The above is the detailed content of How does jQuery dynamically add and delete CSS styles? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete