1.classList
classList对象有下列方法。add():增加一个 class。remove():移除一个 class。contains():检查当前元素是否包含某个 class。toggle():将某个 class 移入或移出当前元素。item():返回指定索引位置的 class。
1.1 add(), remove()
<style> .current{ color:red; } </style><p id="app">hello world</p> <button id="btn">移除class</button> <script> var app = document.getElementById("app"); var btn = document.getElementById("btn"); app.onclick = function(){ this.classList.add("current") //增加 current类,点击文本变色 } btn.onclick = function(){ app.classList.remove("current") // 移除current类,点击按钮取消颜色 } </script>
1.2contains ,toggle
contains():检查当前元素是否包含某个 classtoggle():将某个 class 移入或移出当前元素 <style> .current{ color: red; } </style> <p id="app">hello world</p> <script> var app = document.getElementById("app"); app.onclick = function(){ this.classList.toggle("current")//将current移入 }