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);
  • 相关阅读:
    PS初步学习经验心得记录
    css第四天--复合选择器和样式三大特性
    css第三天--盒子模型
    html第二天--表单控件和表格
    css第二天--字体属性和文本属性
    vue计算属性(computed)
    ant-input的使用
    js-split() 方法
    设计转到前端开发
    $set
  • 原文地址:https://www.cnblogs.com/suitongyu/p/12071887.html
Copyright © 2011-2022 走看看