• 原生js addclass,hasClass,removeClass,toggleClass的兼容


    (function (window) {
    
        'use strict';
    
        // class helper functions from bonzo https://github.com/ded/bonzo
    
        function classReg(className) {
            return new RegExp("(^|\s+)" + className + "(\s+|$)");
        }
    
        // classList support for class management
        // altho to be fair, the api sucks because it won't accept multiple classes at once
        var hasClass,
        addClass,
        removeClass;
    
        if ('classList' in document.documentElement) {
            hasClass = function (elem, c) {
                return elem.classList.contains(c);
            };
            addClass = function (elem, c) {
                elem.classList.add(c);
            };
            removeClass = function (elem, c) {
                elem.classList.remove(c);
            };
        } else {
            hasClass = function (elem, c) {
                return classReg(c).test(elem.className);
            };
            addClass = function (elem, c) {
                if (!hasClass(elem, c)) {
                    elem.className = elem.className + ' ' + c;
                }
            };
            removeClass = function (elem, c) {
                elem.className = elem.className.replace(classReg(c), ' ');
            };
        }
    
        function toggleClass(elem, c) {
            var fn = hasClass(elem, c) ? removeClass : addClass;
            fn(elem, c);
        }
    
        var classie = {
            // full names
            hasClass : hasClass,
            addClass : addClass,
            removeClass : removeClass,
            toggleClass : toggleClass,
            // short names
            has : hasClass,
            add : addClass,
            remove : removeClass,
            toggle : toggleClass
        };
    
        // transport
        if (typeof define === 'function' && define.amd) {
            // AMD
            define(classie);
        } else {
            // browser global
            window.classie = classie;
        }
    
    })(window);

    经测试,兼容IE8以下;

    参考:https://github.com/ded/bonzo

  • 相关阅读:
    学习笔记5_Day09_网站访问量统计小练习
    学习笔记4_ServletContext(重要整个Web应用的动态资源之间共享数据)
    学习笔记03_Day09-----Servle与反射()
    学习笔记2_Day09_servlet的细节
    学习笔记1_Day09_Servlet
    OC对数组排序的方法
    sqlite事务处理
    封装数据库
    JsonModel的使用
    RBAC表
  • 原文地址:https://www.cnblogs.com/jone-chen/p/5952942.html
Copyright © 2020-2023  润新知