JavaScript中设置元素class,添加/删除元素class的方法

方式一、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);

猜你喜欢

转载自www.cnblogs.com/suitongyu/p/12071887.html