<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> <style type="text/css" media="screen"> .red { color: red; } .underline { text-decoration: underline; } .blue { color: blue; } </style> </head> <body> <ul> <li>聽說白雪公主在逃跑</li> <li class="blue">小紅帽在擔心大灰狼</li> <li>聽說瘋帽喜歡愛麗絲</li> <li>丑小鴨會變成白天鵝</li> </ul> <input type="button" value="為第一個元素添加樣式" id="add"> <input type="button" value="為第二個元素移除樣式" id="remove"> <input type="button" value="為第三個元素切換樣式" id="toggle"> <input type="button" value="判斷第四個元素是否包含樣式" id="contain"> <script> window.onload = function () { // querySelector:返回文檔中匹配指定的CSS選擇器的第一元素 // querySelectorAll:返回文檔中匹配的CSS選擇器的所有元素節點列表 // add:為元素添加指定名稱的樣式,一次只能添加一個樣式 document.querySelector("#add").onclick = function () { // classList:當前元素的所有樣式列表-數組 document.querySelector("li").classList.add("red"); document.querySelector("li").classList.add("underline"); } // remove:為元素移除指定名稱的樣式(不是移除class屬性),一次也只能移除一個 document.querySelector("#remove").onclick = function () { document.querySelector(".blue").classList.remove("blue"); } // toggle:切換元素的樣式,如果元素之前沒有指定名稱的樣式則添加,如果有則移除 document.querySelector("#toggle").onclick = function () { document.querySelectorAll("li")[2].classList.toggle("red"); } // contains:判斷元素是否包含指定名稱的樣式,返回true/false document.querySelector("#contain").onclick = function () { var isContain = document.querySelectorAll("li")[3].classList.contains("red"); alert(isContain) } } </script> </body> </html>
