返回列表

addClass与removeClass的单行正则实现

默认分类 2013/11/03 17:35

基本思路: 由于样式名不受空格影响,因此可以添加空格以简化争着表达式

实现方法:为避免重复添加可先删除指定样式然后再添加

addClass如下:

main.className = (' '+main.className.replace(/(\s)/ig,"$1$1")+' ').replace(new RegExp('(\\s'+'my_class'+'\\s)+',"g"),' ').replace(/(\s)+/ig,"$1")+' '+'my_class';

removeClass如下:

main.className = (' '+main.className.replace(/(\s)/ig,"$1$1")+' ').replace(new RegExp('(\\s'+'my_class'+'\\s)+',"g"),' ').replace(/(\s)+/ig,"$1");

注意事项: js字符串中的\s需转义在转义即\\s

bui.addClass = function (element, className) {
    bui.removeClass(element, className);
    element.className = (element.className +' '+ className).replace(/(\s)+/ig,' ');
    return element;
};
// Support * and ?, like bui.removeClass(elem, 'daneden-*');
bui.removeClass = function(element, className) {
    var list = className.replace(/\s+/ig, ' ').split(' '),
        /* Attention: str need two spaces!! */
        str = (' ' + (element.className || '').replace(/(\s)/ig, '  ') + ' '),
        name,
        rex;
    // 用list[i]移除str
    for (var i=0,len=list.length; i < len; i++){
        name = list[i];
        name = name.replace(/(\*)/g,'\\S*').replace(/(\?)/g,'\\S?');
        rex = new RegExp(' '+name + ' ', 'ig');
        str = str.replace(rex, ' ');
    }
    str = str.replace(/(\s)+/ig,' ');
    str = str.replace(/^(\s)+/ig,'').replace(/(\s)+$/ig,'');
    element.className = str;
    return element;
};