js實現給一個標籤添加多個class值

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   使用   ar   art   div   

在寫html跟css的時候,我們會給一些標籤起一些class的名字,但是在寫js的時候可能也會通過cssName操作css樣式,如果只是平常的element.className = "value";的話,那麼之前的定義的class會被置空,css中的樣式就會受到影響,所以,在js中如果有微調css的話,盡量使用element.style來改變。但是如果真的是使用element.className = "value";的話也可以在js中實現給一個標籤添加多個class值,代碼如下:

  

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>js 實現給一個標籤添加多個class</title>    <style>        div{            width:400px;            height:60px;            border:1px solid #000;        }        .one{            background-color: red;        }        .two{            font:italic bold 16px "微軟雅黑";        }        .three{            text-align: center;        }    </style></head><body>    <div id="test">        js 實現給一個標籤添加多個class    </div>    <script>        var test = document.getElementById("test");        test.className += "one";//屬性的className無論有幾個值,在js中都是一個字串,只是有空格而已        test.className += " two";//後續添加的前邊一定要有空格        test.className += " three";        alert(test.className); // one two three        test.className = test.className.replace(/three/,"");//標籤有多個class值的時候,刪除指定的class        alert(test.className);//one two    </script></body></html>
js 實現給一個標籤添加多個class值

typeof  element.className;//String

js實現給一個標籤添加多個class值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.