zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    JS实战 · 表单验证
    JS实战 · 仿css样式选择器
    JS实战 ·  收缩菜单表单布局
    cookie自动登录的实现
    redis 3.2.5单机版安装、使用、systemctl管理Redis启动、停止、开机启动
    yum问题解决
    配置yum镜像源
    shell笔记
    CCIE总结:路由器、交换机
    云主机如何挂在磁盘
  • 原文地址:https://www.cnblogs.com/suitongyu/p/12071887.html
Copyright © 2011-2022 走看看