base.js

microsoft_kk發表於2013-06-25
function $_id(id){return document.getElementById(id)};//$只定義為通過ID返回元素的功能


//-----------------------dom 自定義方法類---------------------------

function dom(obj){//實現自定義類的一個例項,obj為元素的ID或元素本身
    return new customDom(obj);
}

function customDom(obj){//實現元素自定義方法的類,obj為元素的ID或元素本身    
    
    if(typeof(obj) == "string"){
        this.obj = document.getElementById(obj);
    } 
    else if(typeof(obj) == "object"){this.obj = obj;}
    else this.obj = null;
}

//自定義類方法的實現
customDom.prototype={

    //得到元素
    getElem:function(){return this.obj;},
    
    //得到元素真實座標,返回一個陣列[x,y]
    getPosition:function(){
        var position = [0,0]; 
        var obj = this.obj;
        while(obj.offsetParent){         
           position[0] += obj.offsetLeft; 
           position[1] += obj.offsetTop;
           obj = obj.offsetParent; 
        } 
        position[0] + document.body.offsetLeft;
        position[1] + document.body.offsetTop;
        return position;        
    },
    
    //得到元素屬性
    getStyle:function(name){
        var elem = this.obj;
        //如果該屬性存在於style[]中
        if (elem.style[name]){return elem.style[name];} 
        //否則,嘗試IE的方式      
        else if (elem.currentStyle){return elem.currentStyle[name];}
        //或者W3C的方法
        else if (document.defaultView && document.defaultView.getComputedStyle){
        //格式化mame名稱
            name = name.replace(/([A-Z])/g,"-$1");
            name = name.toLowerCase();
            //獲取style物件並取得屬性的值(如果存在的話)
            var s = document.defaultView.getComputedStyle(elem,"");
            return s && s.getPropertyValue(name);
            //否則,就是在使用其它的瀏覽器
        } else{return null;}   
      },
      
    //得到子節點陣列(解決FF等子節點包括空白節點和文字節點的問題)
    getChildren:function(){    
    var AchildNodes = [];
        for(var i = 0;i < this.obj.childNodes.length;i++){
            if(this.obj.childNodes[i].nodeType == 1){
                AchildNodes.push(this.obj.childNodes[i]);
            }
        }
        return AchildNodes;
    },
    
    //得到下一個兄弟節點
    getNextSibling:function(){
          var endBrother = this.obj.nextSibling;
          while(endBrother.nodeType != 1 ){
               endBrother = endBrother.nextSibling;
          }
          return endBrother;          
      },
      
    //得到上一個兄弟節點
    getPreSibling:function(){
          endBrother = this.obj.previousSibling;
          while(endBrother.nodeType != 1){
               endBrother = endBrother.previousSibling;
          }
          return endBrother;          
      },
      
     //通過getElementsByTagName方式得到的元素並轉換為陣列
     getByTagName:function(name){
        var tagNames = this.obj.getElementsByTagName(name);
        var arr = [];
        for(var i = 0;i < tagNames.length;i++){
            arr.push(tagNames[i]);
        }
            return arr;         
     },
     
     //在節點後插入新的兄弟節點
      insertAfter:function(newNode){
            if(this.obj.nextSibling){this.obj.parentNode.insertBefore(newNode, this.obj.nextSibling);}
            else{this.obj.parentNode.appendChild(newNode);}     
      },
      
      //非IE的innerText用textContent;
      text:function(str){
          this.obj.innerText ? this.obj.innerText = str:this.obj.textContent = str;
      },
            //把用getElementsByTagName等方式得到的元素轉換為陣列
      toArray:function(){
            var arr=[];
            for(var i=0;i<this.obj.length;i++){
                arr.push(this.obj[i]);
            }
            return arr;         
      }
}


//------------------------------Array 擴充套件類------------------------------

//copy陣列
Array.prototype.copy = function(){return this.slice();}

//返回陣列中指定字串的索引
Array.prototype.indexof = function(str){    
    for(var q = 0;q < this.length;q++){
        if(this[q] == str){return q;}
    }
    return -1;
}
/*
var a=[1,4,5,7,84,45,35]
alert(a.indexof(5)) //opt 5
*/


//陣列隨機排序    
Array.prototype.aSort = function(method){
    function Sort(a,b){
        if(method == 0 || method == 1){
            if(a > b){if(method == 0){return 1}else{ return -1}}
            if(a < b){if(method == 0){return -1}else{ return 1}}
            else{return 0}        
        }
        else if(method == 2){return Math.random() > .5 ? -1 : 1;}//用Math.random()函式生成0~1之間的隨機數與0.5比較,返回-1或1           
    }
    this.sort(Sort);
}

/*
var a=[1,4,5,7,84,45,35]
a.aSort(2)
alert(a.toString())
*/

//在陣列任意索引處刪除一項    
Array.prototype.delIndex = function(index){this.splice(index,1)}

//在陣列任意索引處刪除多項    
Array.prototype.del = function(){
       var opts = this.sort.call(arguments,Function('a,b','return a > b?-1:1;'));   
       for (var i = 0;i < opts.length;i++ ){this.splice(opts[i],1);}
       return this;
}
/*
var a=['甲','乙','丙','丁'];
alert(a.del(3,1));
*/

//在陣列任意索引後增加一項或多項    
Array.prototype.addIndex = function(index,arr){this.splice(index + 1,0,arr)}

//返回陣列中最大項
Array.prototype.max = function(){
return Math.max.apply({},this);
}

//返回陣列中最小項
Array.prototype.min = function(){
return Math.min.apply({},this);
} 

//------------------------------String 擴充套件類------------------------------

//得到有漢字字串的長度
String.prototype.chLength = function(){
     var strLen = 0;
     for(i = 0;i < this.length;i++){
         if(this.charCodeAt(i) > 255){strLen += 2;}
         else{strLen++;}
     }
     return strLen;
}

//去除敏感字元
String.prototype.trimBadWords = function(str){        
    var reg = new RegExp(str,"gi");
    return this.replace(reg,function(str_bad){return str_bad.replace(/./g,"*")});
}


//去除字串首尾空格
String.prototype.trimSpaces = function(){
    var reg = /^\s*(.*?)\s*$/gim;
    return this.replace(reg,"$1");
}

//轉化<>標籤為實體字元
String.prototype.trimTab = function(){
    var reg = /<|>/g;
    return this.replace(reg,function(s){if(s == "<"){return "&lt;";}else{return "&gt;";}})    
}

//去除任意HTML標籤
String.prototype.trimHtml = function(tag){//不寫標籤名代表所有標籤
    tag ? reg = new RegExp("<\/?"+tag+"(?:(.|\s)*?)>","gi"):reg = /<(?:.|\s)*?>/gi;
    return this.replace(reg,"");
}

//-----------------------event---------------------------
var ev={
          //新增事件監聽
          addEvent:function(obj,evt,fun){
              if(obj.addEventListener){//for dom
                    obj.addEventListener(evt,fun,false)
              }
              else if(obj.attachEvent){//for ie
                     obj.attachEvent("on"+evt,fun)
                    //obj.attachEvent("on"+evt,function(){fun.call(obj)});//解決IE attachEvent this指向window的問題
              }
              else{obj["on"+evt] = fun}//for other
          },
          
          //刪除事件監聽
          removeEvent:function(obj,evt,fun){
              if(obj.removeEventListener){//for dom
                    obj.removeEventListener(evt,fun,false)
              }
              else if(obj.detachEvent){//for ie
                    obj.detachEvent("on"+evt,fun)
              }
              else{obj["on"+evt] = null;
              } //for other
           },
    
          //捕獲事件        
           getEvent:function(){
                    if(window.event){return window.event}
                    else{return ev.getEvent.caller.arguments[0];}    
           },
           
           formatEvent:function(evt){
                    evt.eTarget = evt.target ? evt.target:evt.srcElement;//事件目標物件
                    evt.eX = evt.pagex ? evt.pagex:evt.clientX + document.body.scrollLeft;//頁面滑鼠X座標
                    evt.eY = evt.pagey ? evt.pagex:evt.clientY + document.body.scrollTop;//頁面滑鼠Y座標
                    evt.eStopDefault = function(){this.preventDefault ? this.preventDefault():this.returnValue = false;}//取消預設動作
                    evt.eStopBubble = function(){this.stopPropagation ? this.stopPropagation():this.cancelBubble = true;}//取消冒泡
           }
}


//----------------------------------cookie-----------------------------------
var cookie = {
    //設定cookie
    setCookie:function(sName,sValue,oExpires,sPath,sDomain,bSecure)    {
        var sCookie=sName + "=" + encodeURIComponent(sValue);
        if(oExpires){sCookie += "; expires=" + oExpires.toUTCString();}
        if(sPath){sCookie += "; path="+sPath;}
        if(sDomain){sCookie += "; domain="+sDomain;}    
        if(bSecure){sCookie += "; scure";}
        document.cookie=sCookie;
    },
    
    //讀取cookie
    getCookie:function(sName){
        var sRE="(?:; )?" + sName + "=([^;]*);?";
        var oRE=new RegExp(sRE);
        if(oRE.test(document.cookie)){
            return decodeURIComponent(RegExp["$1"]);
        }
        else{return null;}    
    },
    
    //刪除cookie
    delCookie:function(sName,sPath,sDomain){
        setCookie(sName,"",new Date(0),sPath,sDomain);    
    }
}


//--------------------ajax類---------------------
var XMLHttp = {
    _objPool: [],
    _getInstance: function (){
        for (var i = 0; i < this._objPool.length; i ++){
            if (this._objPool[i].readyState == 0 || this._objPool[i].readyState == 4){
                return this._objPool[i];
            }
        }
        // IE5中不支援push方法
        this._objPool[this._objPool.length] = this._createObj();
        return this._objPool[this._objPool.length - 1];
     },
     _createObj: function (){
        if (window.XMLHttpRequest){ var objXMLHttp = new XMLHttpRequest();}
        else{
             var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
             for(var n = 0; n < MSXML.length; n ++){
                 try {
                     var objXMLHttp = new ActiveXObject(MSXML[n]);
                     break;
                 }
                 catch(e){}
             }
         } 
        // mozilla某些版本沒有readyState屬性
        if (objXMLHttp.readyState == null){
            objXMLHttp.readyState = 0;
            objXMLHttp.addEventListener("load", function (){
               objXMLHttp.readyState = 4;
               if (typeof objXMLHttp.onreadystatechange == "function"){
                   objXMLHttp.onreadystatechange();}
               }, false);
        }
            return objXMLHttp;
    },
    // 傳送請求(方法[post,get], 地址, 資料, 回撥函式, 回撥函式引數-多個用陣列形式)
    sendReq: function (method, url, data, callback,arg){
        var objXMLHttp = this._getInstance();
        with(objXMLHttp){
            try{
                // 加隨機數防止快取
                if (url.indexOf("?") > 0){
                    url += "&randnum=" + Math.random();
                }
                else{url += "?randnum=" + Math.random();}                
                open(method, url, true);
                // 設定請求編碼方式
                setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
                send(data);
                onreadystatechange = function (){
                    if (objXMLHttp.readyState == 4 && (objXMLHttp.status == 200 || objXMLHttp.status == 304)){
                         callback(objXMLHttp,arg);
                    }
               }
           }
           catch(e){alert(e);}
       }
   }
}; 


//js浮點數精確計算函式(加,減,乘,除)//浮點數加法運算  
 function FloatAdd(arg1,arg2){  
   var r1,r2,m;  
   try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}  
   try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}  
   m=Math.pow(10,Math.max(r1,r2));
   return (arg1*m+arg2*m)/m;
  }  ;
  
 //浮點數減法運算  
 function FloatSub(arg1,arg2){  
     var r1,r2,m,n;  
     try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}  
     try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}  
     m=Math.pow(10,Math.max(r1,r2));  
     //動態控制精度長度  
     n=(r1>=r2)?r1:r2;  
     return ((arg1*m-arg2*m)/m).toFixed(n);  
 } ; 
   
 //浮點數乘法運算  
 function FloatMul(arg1,arg2) {   
      var m=0,s1=arg1.toString(),s2=arg2.toString();   
      try{m+=s1.split(".")[1].length}catch(e){}   
      try{m+=s2.split(".")[1].length}catch(e){}   
      return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)   
  }  ; 
  
  
//浮點數除法運算  
function FloatDiv(arg1,arg2){   
    var t1=0,t2=0,r1,r2;   
    try{t1=arg1.toString().split(".")[1].length}catch(e){}   
    try{t2=arg2.toString().split(".")[1].length}catch(e){}   
    with(Math){   
        r1=Number(arg1.toString().replace(".","")) ;  
        r2=Number(arg2.toString().replace(".",""));   
        return (r1/r2)*pow(10,t2-t1);   
    }   
} ;