美文网首页
封装: addClass()-removeClass()

封装: addClass()-removeClass()

作者: 阿九是只大胖喵 | 来源:发表于2017-03-12 16:11 被阅读0次
        // -> hasClass: 验证当前元素中是否包含className这个样式类名
        function hasClass(curEle, className) {
            var reg = new RegExp("(^| +)" + className + "( +|$)");
            return reg.test(curEle.className);
        }
    
        // -> addClass: 给元素增加样式类型
        function addClass(curEle, className) {
            var ary = className.split(/\s+/g);
    
            // -> 循环数组,一项一项的验证
            for (var i = 0, len = ary.length; i < len; i++) {
                var curName = ary[i];
                if (!hasClass(curEle, curName)) {
                    curEle.className += ' ' + curName;
                }
            }
        }
    
        // -> removeClass: 给元素移除样式类型
        function removeClass(curEle, className) {
            var ary = className.split(/\s+/g);
            for (var i = 0, len = ary.length; i < len; i++) {
                var curName = ary[i];
                if (hasClass(curEle, curName)) {
                    var reg = new RegExp("(^| +)" + curName + "( +|$)", "g");
                    curEle.className = curEle.className.replace(reg, ' ');
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:封装: addClass()-removeClass()

          本文链接:https://www.haomeiwen.com/subject/czatnttx.html