JavaScript动态修改css样式的四种方法学习笔记

1,obj.style.backgroundColor = ("black");这种方式会覆盖之前的样式

2,obj.style.cssText = " color : white;";这种方式会覆盖之前的样式,,用追加来解决这个问题:

    obj.style.cssText += "color: white;";但在IE中是无效的,可以在前面添加一个分号解决:

    obj.style.cssText += ";color: white;";

    再进一步,如果前面有样式表文件写着 div { text-decoration:underline; },这个会被覆盖吗?不会!因为它不是直接作用于 HTML 元素的 style 属性

3,通过修改类名:obj.className = "style2"; 或者obj.setAttribute("class","style2"); 这会替换之前的样式,如果要追加,则:

function addClass(element,value) {
    if (!element.className) {
        element.className = value;
    } else {
        newClassName = element.className;
        newClassName += " "; //这句代码追加的类名分开
        newClassName += value;
        element.className = newClassName;
    }
}

4,使用更改外联的css文件:obj.setAttribute("href","css2.css");

猜你喜欢

转载自blog.csdn.net/x1151605848/article/details/81518658
今日推荐