封装框架-类选择器 四种方法添加、移除、判断、替换

//封装框架类操作   1. addClass(添加类)
//                 2.removeClass(移除样式)
//                 3. hasClass(判断是否有这个样式)
//                 4.toggleClass(有这个类就移除,没有就添加个新的)

//例:itcast(div).addClass("类名")


//样式操作模块

    itcast.fn.extend({
       css:function(name,value){
           //第二个参数没有传入 ,而第一个参数是字符串
           if(value === undefined && typeof name ==="string"){
           //查询,有兼容问题 两种兼容
               if(window.getComputedStyle){
                    var styles = window.getComputedStyle(this[0]);
                   return styles[name];
               }else {
                   return this[0].currentStyle[name];
               }
           }

       // 如果设置了值
           this.each(function(){
               //第一个参数如果是 对象

               if(value === undefined && typeof name ==="object"){
                   for(var k in name){
                       this.style[k] = name[k];
                   }
               }else {
                    this.style[name] = value;
               }
           })

           return this;

       },
        //添加类样式
        addClass:function(cName){
            this.each(function(){
                var clsName = this.className;
                clsName +=" "+ cName;
                this.className = itcast.trim(clsName);
            })
            return this;
        },
    //    移除样式
        removeClass:function(cName){
            this.each(function(){

                var claName = " " +this.className+" ";
                claName = claName.replace(" "+cName+" "," ");
                console.log(claName);
                this.className = itcast.trim(claName);
            })

            return this;
        },
        //如果有这个类就返回true 没有就返回false
        hasClass:function(cName){
            var hasCls = false;
            this.each(function(){
                var claName = this.className;
                hasCls = (" "+claName+" ").indexOf(" "+cName+" ") !==-1;
                if(hasCls){
                    return false;
                }
            })
            return hasCls;
        },
        //判断是否有这个类有就移出,没有就添加一个新的
        toggleClass:function(cName){
            this.each(function(){
                if(itcast(this).hasClass(cName)){
                            itcast(this).removeClass(cName);
                }else{
                    itcast(this).addClass(cName);
                }
            })
        }
    });

猜你喜欢

转载自ning-wenchao.iteye.com/blog/2318088