原生JavaScript实现hasClass、addClass、removeClass、toggleClass



兼容IE6+,因IE6、IE7、IE8不支持Array.prototype.indexOf()String.prototype.trim(),分别用Polyfill实现支持。
详细:
indexOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
trim: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

由于现在浏览器都基本支持了classList,所以移动端可以直接使用classList会更方便一些,如:

<div class="foo bar" id="div"></div>
var div = document.getElementById(‘div‘);

div.classList.remove("foo");
div.classList.add("anotherclass");
div.classList.toggle("visible");

div.classList.contains("foo");   //

div.classList.add("foo","bar");  //Android4.3不支持
  1. 应该避免直接使用多个参数,支持不全面。
  2. SVG 和 MathML 元素支持度也不全面(这个坑下面的代码并未填上,请熟知,有兴趣的可以查下Zepto是怎么填坑的)。
    classList支持明细: http://caniuse.com/#search=classList

代码

Polyfill

// 让低版本IE支持 Array.prototype.indexOf
// Polyfill (indexOf @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
  if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(searchElement, fromIndex) {

      var k;
      if (this == null) {
        throw new TypeError(‘"this" is null or not defined‘);
      }

      var o = Object(this);
      var len = o.length >>> 0;
      if (len === 0) {
        return -1;
      }

      var n = +fromIndex || 0;
      if (Math.abs(n) === Infinity) {
        n = 0;
      }

      if (n >= len) {
        return -1;
      }

      k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      while (k < len) {
        if (k in o && o[k] === searchElement) {
          return k;
        }
        k++;
      }
      return -1;
    };

  }

  // 让低版本IE支持 String.prototype.trim()
  // Polyfill (trim @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  if (!String.prototype.trim) {
    String.prototype.trim = function(){
      return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ‘‘);
    };
  }

支持 classList 实现方式

function ctrlClass(opts) {
    if (!opts.ele || !opts.c) return false;
    // console.log(opts.c)
    var c = null;
    typeof (opts.c) === ‘string‘ ?
    c = opts.c.trim().replace(/\s+/g, ‘ ‘).split(‘ ‘) :
    c = opts.c;  //修复不规范传参

    return opts.fun({
        ele: opts.ele,
        c: c
    });
    opts.ele = null;
}

/**
 * hasClass
 * @param (element, ‘c1 c2 c3 c4 c5‘)
 */
 function hasClass(ele, c) {
    return ctrlClass({
        ele: ele,
        c: c,
        fun: function(opts) {
            return opts.c.some(function(v) {
                return !!opts.ele.classList.contains(v);
            });
        }
     });
 }

 /**
 * addClass
 * @param (element, ‘c1 c2 c3 c4 c5‘)
 */
 function addClass(ele, c) {
    return ctrlClass({
        ele: ele,
        c: c,
        fun: function(opts) {
            var ele = opts.ele,
                c = opts.c;
            c.forEach(function(v) {
                if (!hasClass(ele, v)) {
                    ele.classList.add(v);
                }
            });
        }
    })
 }

 /**
  * removeClass
  * @param (element, ‘c1 c2 c3‘)
 */
 function removeClass(ele, c) {
  ctrlClass({
    ele: ele,
    c: c,
    fun: function(opts) {
      var ele = opts.ele,
          c = opts.c;
      c.forEach(function(v) {
        // TODO 是否有必要判断 hasClass
        // if (!hasClass(ele, v)) {
          ele.classList.remove(v);
        // }
      });
    }
  });
 }

 /**
  * toggleClass
  * @param (element, ‘c1 c2 c3‘)
 */
 function toggleClass(ele, c) {
  ctrlClass({
    ele: ele,
    c: c,
    fun: function(opts) {
      var ele = opts.ele,
          c = opts.c;
      c.forEach(function(v) {
        ele.classList.toggle(v);
      })
    }
  })
 }

不支持 classList 实现方式

/**
 * hasClass
 * @param (element, ‘c1 c2 c3 c4 c5‘)
 */
 function hasClass(ele, c) {
    return ctrlClass({
        ele: ele,
        c: c,
        fun: function(opts) {
            var cln = opts.ele.className.split(‘ ‘);
            var c = opts.c;
            for (var i = 0; i < c.length; i++) {
                if(cln.indexOf(c[i]) !== -1){
                    return true;
                }
            }
            return false;
        }
     });
 }

 /**
  * addClass
  * @param (element, ‘c1 c2 c3‘)
 */
 function addClass(ele, c) {
  ctrlClass({
    ele: ele,
    c: c,
    fun: function(opts) {
      var ele = opts.ele,
          c = opts.c;
      for (var i = 0; i < c.length; i++) {
        if(!hasClass(ele, c[i])) {
          ele.className = ele.className !== ‘‘ ? (ele.className + ‘ ‘ + c[i]) : c[i];
        }
      }
    }
  });
 }

 /**
  * removeClass
  * @param (element, ‘c1 c2 c3‘)
 */
 function removeClass(ele, c) {
  ctrlClass({
    ele: ele,
    c: c,
    fun: function(opts) {
      var ele = opts.ele,
          c = opts.c,
          cln = ele.className.split(‘ ‘);
      for (var i = 0; i < c.length; i++) {
        if (hasClass(ele, c[i])) {
          cln.splice(cln.indexOf(c[i]), 1);
        }
      }
      ele.className = cln.join(‘ ‘);
    }
  });
 }

 /**
  * toggleClass
  * @param (element, ‘c1 c2 c3‘)
 */
 function toggleClass(ele, c){
  ctrlClass({
    ele: ele,
    c: c,
    fun: function(opts) {
      var ele = opts.ele,
          c = opts.c;
      for (var i = 0; i < c.length; i++) {
        !!hasClass(ele, c[i]) ? removeClass(ele, c[i]) : addClass(ele, c[i]);
      }
    }
  });
 }

完整代码

// Polyfill (indexOf @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {

  var k;
  if (this == null) {
    throw new TypeError(‘"this" is null or not defined‘);
  }

  var o = Object(this);
  var len = o.length >>> 0;
  if (len === 0) {
    return -1;
  }

  var n = +fromIndex || 0;
  if (Math.abs(n) === Infinity) {
    n = 0;
  }

  if (n >= len) {
    return -1;
  }

  k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

  while (k < len) {
    if (k in o && o[k] === searchElement) {
      return k;
    }
    k++;
  }
  return -1;
};

}

  // Polyfill (trim @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)
  if (!String.prototype.trim) {
    String.prototype.trim = function(){
      return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ‘‘);
    };
  }

var cl = (‘classList‘ in document.createElement(‘a‘));

function ctrlClass(opts) {
    if (!opts.ele || !opts.c) return false;
    // console.log(opts.c)
    var c = null;
    typeof (opts.c) === ‘string‘ ?
    c = opts.c.trim().replace(/\s+/g, ‘ ‘).split(‘ ‘) :
    c = opts.c;  //修复不规范传参

    return opts.fun({
        ele: opts.ele,
        c: c
    });
    opts.ele = null;
}   

// 支持 classList
if(cl){
    /**
     * hasClass
     * @param (element, ‘c1 c2 c3 c4 c5‘)
     */
     function hasClass(ele, c) {
        return ctrlClass({
            ele: ele,
            c: c,
            fun: function(opts) {
                return opts.c.some(function(v) {
                    return !!opts.ele.classList.contains(v);
                });
            }
         });
     }

     /**
     * addClass
     * @param (element, ‘c1 c2 c3 c4 c5‘)
     */
     function addClass(ele, c) {
        return ctrlClass({
            ele: ele,
            c: c,
            fun: function(opts) {
                var ele = opts.ele,
                    c = opts.c;
                c.forEach(function(v) {
                    if (!hasClass(ele, v)) {
                        ele.classList.add(v);
                    }
                });
            }
        })
     }

     /**
      * removeClass
      * @param (element, ‘c1 c2 c3‘)
     */
     function removeClass(ele, c) {
      ctrlClass({
        ele: ele,
        c: c,
        fun: function(opts) {
          var ele = opts.ele,
              c = opts.c;
          c.forEach(function(v) {
            // TODO 是否有必要判断 hasClass
            // if (!hasClass(ele, v)) {
              ele.classList.remove(v);
            // }
          });
        }
      });
     }

     /**
      * toggleClass
      * @param (element, ‘c1 c2 c3‘)
     */
     function toggleClass(ele, c) {
      ctrlClass({
        ele: ele,
        c: c,
        fun: function(opts) {
          var ele = opts.ele,
              c = opts.c;
          c.forEach(function(v) {
            ele.classList.toggle(v);
          })
        }
      })
     }

}else{
    /**
     * hasClass
     * @param (element, ‘c1 c2 c3 c4 c5‘)
     */
     function hasClass(ele, c) {
        return ctrlClass({
            ele: ele,
            c: c,
            fun: function(opts) {
                var cln = opts.ele.className.split(‘ ‘);
                var c = opts.c;
                for (var i = 0; i < c.length; i++) {
                    if(cln.indexOf(c[i]) !== -1){
                        return true;
                    }
                }
                return false;
            }
         });
     }

     /**
      * addClass
      * @param (element, ‘c1 c2 c3‘)
     */
     function addClass(ele, c) {
      ctrlClass({
        ele: ele,
        c: c,
        fun: function(opts) {
          var ele = opts.ele,
              c = opts.c;
          for (var i = 0; i < c.length; i++) {
            if(!hasClass(ele, c[i])) {
              ele.className = ele.className !== ‘‘ ? (ele.className + ‘ ‘ + c[i]) : c[i];
            }
          }
        }
      });
     }

     /**
      * removeClass
      * @param (element, ‘c1 c2 c3‘)
     */
     function removeClass(ele, c) {
      ctrlClass({
        ele: ele,
        c: c,
        fun: function(opts) {
          var ele = opts.ele,
              c = opts.c,
              cln = ele.className.split(‘ ‘);
          for (var i = 0; i < c.length; i++) {
            if (hasClass(ele, c[i])) {
              cln.splice(cln.indexOf(c[i]), 1);
            }
          }
          ele.className = cln.join(‘ ‘);
        }
      });
     }

     /**
      * toggleClass
      * @param (element, ‘c1 c2 c3‘)
     */
     function toggleClass(ele, c){
      ctrlClass({
        ele: ele,
        c: c,
        fun: function(opts) {
          var ele = opts.ele,
              c = opts.c;
          for (var i = 0; i < c.length; i++) {
            !!hasClass(ele, c[i]) ? removeClass(ele, c[i]) : addClass(ele, c[i]);
          }
        }
      });
     }
}

使用

var ele = document.getElementById(‘test‘);
hasClass(ele, ‘c1‘);
addClass(ele, ‘c1 c2 c3‘);
removeClass(ele, ‘c1 c2 c3‘);
toggleClass(ele, ‘c1 c2 c3‘);

项目

https://github.com/givebest/ctrl-cssClass

时间: 2024-11-05 06:15:58

原生JavaScript实现hasClass、addClass、removeClass、toggleClass的相关文章

原生javascript实现 hasClass addClass removeClass

function hasClass(elem, cls) { cls = cls || ''; if (cls.replace(/\s/g, '').length == 0) return false; return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' '); } function addClass(ele, cls) { if (!hasClass(elem, cls)) { ele.className = ele

原生JavaScript实现的addclass,removeclass,hasclass,toggleclass,getbyclass

<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>addclass,removeclass,hasclass,toggleclass,getbyclass</title> </head> <body> <div class="div1" id="b

原生JS实现hasClass,addClass,removeClass

1.hasClass function hasClass(elem, cls){     cls = cls || '';     if(cls.replace(/\s/g, '').length == 0) return false;     return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' '); } 2.addClass function addClass(elem, cls){     if(!hasClas

原生JS实现addClass,removeClass,toggleClass

<style type="text/css"> div.testClass{ background-color:gray; } </style> <script type="text/javascript"> function hasClass(obj, cls) { return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); } function ad

.addClass(),.removeClass(),.toggleClass()的区别

.addClass("className")方法是用来给指定元素增加类名,也就是说给指定的元素追加样式: 可以同时添加多个类名,空格符隔开 $("selector").addClass("className1 className2"); .removeClass("className")方法是用来给指定的元素移除类名,也就是说给指定元素移除样式: 可以同时移除多个类名,空格符隔开 $("selector")

class 添加样式,删除,开关 【选择】addClass,removeClass,toggleClass

<1> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="script/jquery-1.11.0.min.js" type="text/javascript"></script> <style type="text/css"&g

addClass, removeClass, toggleClass(从jquery中抠出来)

<div id="d3" class="cur"></div> 1 var mylibs = (function(){ 2 var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, 3 core_trim = String.prototype.trim, 4 core_rspace = /\s+/, 5 rclass = /[\t\r\n]/g; 6 7 var trim = function(tex

jQuery addClass removeClass toggleClass方法概述

通过动态改变类名(class),可以让其修改元素呈现出不同的效果.在HTML结构中里,多个class以空格分隔,当一个节点(或称为一个标签)含有多个class时,DOM元素响应的className属性获取的不是class名称的数组,而是一个含有空格的字符串,这就使得多class操作变得很麻烦.同样的jQuery开发者也考虑到这种情况,增加了一个.addClass()方法,用于动态增加class类名 .addClass( className )方法 .addClass( className ) :

hasClass addClass removeClass

//函数有class function hasClass(ele,cls){ return -1<(" "+ele.className+" ").indexOf(" "+cls+" ") } //添加class function addClass(ele,cls){ if((" "+ele.className+" ").indexOf(" "+cls+"