標籤: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值