方式一、el.setAttribute('class','a');
.a{ color: red; } #id box var box = document.getElementById('box'); box.setAttribute('class','a');
IE6/7 : div背景色不是紅色
IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色為紅色
結果:IE6/7不支持setAttribute('class','xxx')方式設置元素的class。
方式二、el.setAttribute('className', 'a');
.a{ color: red; } #id box var box = document.getElementById('box'); box.setAttribute('className','a');
IE6/7 : div背景色為紅色
IE8/9/10/Firefox/Safari/Chrome/Opera : div背景色不是紅色
結果:IE8/9/10/Firefox/Safari/Chrome/Opera不支持setAttribute('className','xxx')方式設置元素的class。
注意:以上兩種方式都存在兼容性問題
方式三、el.className = 'abc';(兼容性好)
.a{ color: red; } .b{ font-size: 18px; } #id box var box = document.getElementById('box'); box.className = 'a'; box.className += ' b'; //前加空格
結果:所有瀏覽器都支持。
除此之外還有其他方式
使用 el.classList 添加和刪除class
.a{ color: red; } .b{ font-size: 18px; } .c{ background: #8A2BE2; } #id box var box = document.getElementById('box'); //console.log(box.classList); box.classList.add('a'); //添加 box.classList.remove('b'); //刪除 box.classList.toggle('c') //如果有相應的class就刪除,沒有就添加 var if_b = box.classList.contains('a'); //查找有沒有相應的 class,返回true/false console.log(if_b);