HTML5 - 类名API

作者: Hyso | 来源:发表于2019-03-04 15:26 被阅读0次
    给当前元素添加类样式
    • 语法
    Element.classList.add("类名");
    
    • 示例
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
        <style type="text/css">
        .red {
            color: red;
        }
        </style>
    </head>
    <body>
    <div id="username">Peter</div>
    <button id="change">改变样式</button>
    
    <script>
        document.querySelector("#change").onclick = function()
        {
            document.querySelector("#username").classList.add("red");
        }
    </script>
    </body>
    </html>
    
    给当前元素移除类样式
    • 语法
    Element.classList.remove("类名");
    
    • 示例
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
        <style type="text/css">
        .red {
            color: red;
        }
        </style>
    </head>
    <body>
    <div id="username" class="red">Peter</div>
    <button id="change">改变样式</button>
    
    <script>
        document.querySelector("#change").onclick = function()
        {
            document.querySelector("#username").classList.remove("red");
        }
    </script>
    </body>
    </html>
    
    检测当前元素添是否包含类样式
    • 语法
    Element.classList.contains("类名");
    
    • 示例
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
        <style type="text/css">
        .red {
            color: red;
        }
        .blue {
            color: blue;
        }
        </style>
    </head>
    <body>
    <div id="username" class="red">Peter</div>
    <button id="change">改变样式</button>
    
    <script>
        var selector = document.querySelector("#username");
    
        document.querySelector("#change").onclick = function()
        {
            if (selector.classList.contains("red")) {
                selector.classList.remove("red");
                selector.classList.add("blue");
            }
        }
    </script>
    </body>
    </html>
    
    给当前元素切换类样式:有就删除,没有就添加
    • 语法
    Element.classList.toggle("类名");
    
    • 示例
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>test</title>
        <style type="text/css">
        .red {
            color: red;
        }
        </style>
    </head>
    <body>
    <div id="username" class="red">Peter</div>
    <button id="change">改变样式</button>
    
    <script>
        document.querySelector("#change").onclick = function()
        {
            document.querySelector("#username").classList.toggle("red");
        }
    </script>
    </body>
    </html>
    

    相关文章

      网友评论

        本文标题:HTML5 - 类名API

        本文链接:https://www.haomeiwen.com/subject/hhriuqtx.html