JavaScript学习-封装基础库3

版权声明:本文为博主原创文章,欢迎转载。 https://blog.csdn.net/fww330666557/article/details/78787009

CLASS的添加

demo.css:

.a {
    color: red;
}
.b {
    background: #ccc;
}
.c {
    font-weight: bold;
}
.d {
    text-decoration: underline;
}

demo.html:

<div id='box'>box</div>
<div id='pox'>pox</div>

demo.js:

 $().getId('box').addClass('a').addClass('b').addClass('a');

base.js:

// 添加CLASS
Base.prototype.addClass = function(className){
    for(var i = 0; i < this.elements.length; i++){
       // 正则避免重复添加
        if(!this.elements[i].className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'))){
            this.elements[i].className += ' ' + className;
        }
    }
    return this;
}

CLASS的移除

demo.js:

 $().getId('box').addClass('a').addClass('b').addClass('a').removeClass('a');

base.js:

// 移除CLASS
Base.prototype.removeClass = function(className){
    for(var i = 0; i < this.elements.length; i++){
        if(this.elements[i].className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'))){
            this.elements[i].className = this.elements[i].className.replace(new RegExp('(\\s|^)'+className+'(\\s|$)'),'');
        }
    }
    return this;
}

link或style中的CSS的添加和删除

添加

demo.js:

$().addRule(0,'body','background:green',0);

base.js:

// 添加link或style的CSS规则
Base.prototype.addRule = function(num,selectorText,cssText,position){
    var sheet = document.styleSheets[num];
    if(typeof sheet.insertRule != 'undefined'){// w3c
        sheet.insertRule(selectorText + '{' + cssText +'}',position);
    }else if(typeof sheet.addRule != 'undefined'){//IE
        sheet.addRule(selectorText,cssText,position);
    }
    return this;
}

移除

demo.js:

$().removeRule(0);

base.js:

// 移除link或style的CSS规则
Base.prototype.removeRule = function(num,index){
    var sheet = document.styleSheets[num];
    if(typeof sheet.deleteRule != 'undefined'){// w3c
        sheet.deleteRule(index);
    }else if(typeof sheet.removeRule != 'undefined'){//IE
        sheet.removeRule(index);
    }
    return this;
}

web应用中很少用到添加和删除CSS规则的操作,因为添加和删除原本的规则会破坏整个CSS的结构,所以使用要非常小心。

猜你喜欢

转载自blog.csdn.net/fww330666557/article/details/78787009