封装库--CSS(下)

34项目1-博客前端:封装库--CSS[]

 

学习要点:

1.获取节点问题

2.继续封装CSS

 

 

 

本节课,我们继续封装CSS,主要探讨添加class和移除class。并且能够添加style和link元素的css规则。

 

一.获取节点问题

在获取ID、TagName、Class节点上,我们把this.elements放到了外部,导致实例化的this.elements变成了公有化,所以,这个数组,我们必须放到内部。

 

二.继续封装CSS

在节点上添加一个class,这个知识点我们在之前已经学习过:

//添加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

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规则

Base.prototype.addRule = function (num, selectorText, cssText, position) {

       var sheet = document.styleSheets[num];

       if (typeof sheet.insertRule != 'undefined') {

              sheet.insertRule(selectorText + "{" + cssText + "}", position);

       } else if (typeof sheet.addRule != 'undefined') {

              sheet.addRule(selectorText, cssText, position);

       }

};

 

//移除link或style中的CSS规则

Base.prototype.removeRule = function (num, index) {

       var sheet = document.styleSheets[num];

       if (typeof sheet.deleteRule != 'undefined') {

              sheet.deleteRule(index);

       } else if (typeof sheet.removeRule) {

              sheet.removeRule(index);

       }

       return this;

};

 

PS:在Web应用中,很少用到添加CSS规则和移除CSS规则,一般只用行内和Class;因为添加和删除原本的规则会破坏整个CSS的结构,所以使用需要非常小心。

转载于:https://www.cnblogs.com/dingruinb/p/6408203.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值