JavaScript編程開發中常用的js

JavaScript編程開發中常用的js。

1.轉中文編碼

function mspGb2312(key)
{
    var r = "";
    for(var i=0;i=0x4e00 || t==0x300A || t==0x300B)
        {
            try
            {
                execScript("ascCode=hex(asc(\""+key.charAt(i)+"\"))", "vbscript"); r += ascCode.replace(/(.{2})/g, "%$1"); }
            catch(e)
            {}
        }
        else{r += escape(key.charAt(i));}
    }
    return r;
}

2.//判斷字符串是否為數字

var isIntNumber = function(String){
    var Letters = "1234567890";
    var i;   
    var c;    
    for( i = 0; i < String.length; i ++ )   
    {     
        c = String.charAt( i );   
        if (Letters.indexOf( c ) < 0)   
            return false;   
    }
    return true;        
};

function trim(str){
    if (typeof(str) != "undefined")
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

3.判斷字符串是否符合郵件地址格式

var isEmail = function(strEmail)
{
    if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)   
        return true;   
    else   
        return false;       
};

4.判斷是否是域名

var isDomain = function(strDomain){
    return(/^[-0-9a-zA-Z]+(\.[-0-9a-zA-Z]+)+(\/([-0-9a-zA-Z]+\.*[0-9a-zA-Z]+)*)*$/.test(strDomain))
}

var isMobile = function(mobile) {
    return (/^1[3|4|5|8|7][0-9]\d{8}$/.test(mobile));
};

5.判斷是否是固定電話

var isTel = function(tel) {
    return (/^([0-9]{3,4}-)?[0-9]{7,8}$/.test(tel));
};

6.輸入的回車換行和空格字符轉換成html格式標簽

function  transformHtml(str){
    // 將字符串以正確方式顯示(包括回車,換行,空格)
    while(str.indexOf("\n")!=-1){
    str = str.substring(0,str.indexOf("\n"))+"
"+str.substring(str.indexOf("\n")+1);
    }
    while(str.indexOf(" ")!=-1){
    str = str.substring(0,str.indexOf(" "))+" "+str.substring(str.indexOf(" ")+1);
    }
    return str;
}

7.iframe高度自適應

function iFrameHeight(iframeid) {
    var ifm = document.getElementById(iframeid);

    if(ifm.src!="#"){
        var subWeb = document.frames ? document.frames[iframeid].document : ifm.contentDocument;
        if(ifm != null && subWeb != null) {
            ifm.height = subWeb.body.scrollHeight;
        }
    }
}

8.js 數字 千位分組

function number_format(str) {
    str = String(str);
    var str1="";
    if(str.indexOf(".")>-1){
        str1=str.replace(/(\d*)(.\d*)/,"$2");
        str1=str1.replace(/(\d{1,3})/g,"$1,");
        str1 = str1.replace(/,$/, '');
        str =str.replace(/(\d*)(.\d*)/,"$1");
    }
    str = str.replace(/(?=(?:\d{3})+(?!\d))/g, ',');
    str = str.replace(/^,/, '');
    str+=str1;
    return str;

}

9.歷史回退

function historyBack(str,hrefStr){
    var href=document.referrer;
    if(href.indexOf(str)>-1){
        window.location=href;
    }else{
        window.location=hrefStr;
    }
}

10.

/**
 * 繼續瀏覽廣告
 * imgDivId:包含切換圖片的p的id
 * imgIndex:廣告圖片的index,-1代表當前圖片的下一張,
 * num:圖片個數
 * direc:0->漸變,1->左右,2->上下
 * speed:切換速去
 */
 function continueSwitchPic(imgDivId,imgIndex,direc,speed){
    var num=$("#"+imgDivId+" .switchbtns .abtns").length;
    //curImgIndex:當前圖片的index
    var curImgIndex=$("#"+imgDivId+" .switchbtns .abtns").index($("#"+imgDivId+" .switchbtns .curbtn"));
    if(imgIndex==curImgIndex){
        return 0;
    }
    if(!speed&&speed!=0){
        speed=1000;
    }
    if(imgIndex<0){
        imgIndex=(curImgIndex==(num-1))?0:(curImgIndex+1);
    }
    if(!direc){
        //切換按鈕選中式樣
        $("#"+imgDivId+" .switchbtns .curbtn").removeClass("curbtn");
        $("#"+imgDivId+" .switchbtns .abtns:eq("+imgIndex+")").addClass("curbtn");
        var curObj=$("#"+imgDivId+" .imgsp .curimg"),nextObj=$("#"+imgDivId+" .imgsp .showimg:eq("+imgIndex+")");
        if(speed!=0){
            nextObj.css({opacity:"0",filter:"alpha(opacity=0)"});
            curObj.stop().animate({opacity:"0",filter:"alpha(opacity=0)"},speed);
            nextObj.stop().animate({opacity:"1",filter:"alpha(opacity=100)"},speed);
        }
        curObj.removeClass("curimg");
        nextObj.addClass("curimg");
    }
}

/**
 * tab切換
 */
function switchTab(tabsContentId,callback){
    var thisObj=$(this),
        index=thisObj.index(),
        tabsContentObj=$("#"+tabsContentId);
    thisObj.siblings().removeClass("active");
    thisObj.addClass("active");
    tabsContentObj.children(".tab").css("display","none");
    tabsContentObj.children(".tab").eq(index).css("display","block");
    if(callback){
        callback(thisObj,tabsContentId);
    }
}

11. 判斷包含多少個字節

function getBytesCount(str) 
{ 
    if (str == null) 
    { 
        return 0; 
    }else{ 
        var enterLen = 0;
        if(navigator.userAgent.indexOf("WebKit")>0){
            enterLen = str.length-str.replace(/\n/g, "").length;
        }
        return (str.length + str.replace(/[\u0000-\u00ff]/g, "").length + enterLen);
        // return  str.length + str.replace(/[^\u0080-\u07FF]/g, "").length + str.replace(/[^\u0800-\uFFFF]/g, "").length*2 + enterLen;
    } 
} 

12.截取指定字節數的字符串

function getStrBytesCount(str,account)
{
  var bytesCount = 0,thisByteCount=0;
  if (str != null)
  {
    for (var i = 0; i < str.length; i++){
        var c = str.charAt(i);
        //0000 - 007F 0xxxxxxx
        // 0080 - 07FF 110xxxxx 10xxxxxx
        // 0800 - FFFF 1110xxxx 10xxxxxx 10xxxxxx
        // if(/^[\u0000-\u007F]$/.test(c)){
        //  thisByteCount= 1;
        // }else if(/^[\u0080-\u07FF]$/.test(c)){
        //  thisByteCount= 2;
        // }else if(/^[\u0800-\uFFFF]$/.test(c)){
        //  thisByteCount= 3;
        // }
        if (/^[\u0000-\u00ff]$/.test(c)){
            if(navigator.userAgent.indexOf("WebKit")>0 && c=='\n'){
                thisByteCount= 2;
            }else{
                thisByteCount= 1;
            }
        }else{
            thisByteCount= 2;
        }
        if(thisByteCount+bytesCount > account){
            bytesCount=i;
            break;              
        }else{
            bytesCount += thisByteCount;
        }
    }
     return str.substr(0, bytesCount);
  }
    return "";
 }

13.點擊贊的動畫

function zanAnimate(x,y,time,color,text){
    var obj=$("#like_1");
    if(!obj.length){
        $("html body").append("+1");
        obj=$("#like_1");
    }
    if(!color||color==""){
        color="#a4d754";
    }
    if(!text||text==""){
        text="+1";
    }
    obj.text(text);
    obj.css({"top":y+"px","left":x+"px","display":"block","opacity":"1","filter":"alpha(opacity=100)","font-size":"20px","color":color});
    obj.stop().animate({"opacity":"0.8","filter":"alpha(opacity=80)","font-size":"30px","top":(y-25)+"px","left":(x-10)+"px"},time,function(){
        obj.css("display","none");
    });
}



var textWidth = function(text){ 
    var htmlcode = $('

'+ (transformHtml(text))+"1" +'

').css({display:"block"}); $('body').append(htmlcode); var width = htmlcode.width(); var height = htmlcode.height(); htmlcode.remove(); return [width,height]; };

14

/**
 * url:跳轉地址
 * loginFlag:是否登錄
 * blankFlag:是否另打開一個頁面
 */
function openPage(url, loginFlag, blankFlag){
    if(loginFlag == "1" || loginFlag == 1){
        judgeLogin();
        if(!userLogin){
            loginLogoutCallBack['loginByOtherCB']=function(){
                window.open(url,blankFlag);
            }
            return 0;
        }else{
            window.open(url,blankFlag);
        }
    }else{
        window.open(url,blankFlag);
    }

}

15.前端獲取文件大小

/*
* 前端獲取文件大小
*/
function getFileSize(obj) {
    var objValue = obj.value;
    if (objValue == "") return;
    var fileLenth = -1;
    try {
        //對於IE判斷要上傳的文件的大小
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        fileLenth = parseInt(fso.getFile(objValue).size);
    } catch (e) {
        try {
            //對於非IE獲得要上傳文件的大小
            fileLenth = parseInt(obj.files[0].size);
        } catch (e) {
            fileLenth = -1;
        }
    }
    return fileLenth;
}

16.獲得地址欄中指定參數名稱的參數值

function getQueryString(name, search){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     search = search || window.location.search;
     var r = search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

17.設置地址欄中指定參數名稱的參數值

function setQueryString(key, value, url){
    url = url || window.location.href;
    var reg = new RegExp(key+"=\\w*","g");
    var keyValue = key+'='+value;
    if(url.indexOf("?")>-1){
        if(url.indexOf(key)>-1){
            url = url.replace(reg,keyValue);
        }else{
            url += "&"+keyValue;
        }
    }else{
        url += "?"+keyValue;
    }
    return url;
}

18.展示或收縮指定元素

function showHideTip(containId, callback){
    var thisObj = $(this);
    var containObj = $("#"+containId);
    $(".show-hide-help:not(#"+containId+")").hide("normal");
    containObj.toggle("normal");
    if(callback){
        callback(thisObj, containObj);
    }
}


Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小時 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    o['M+'] = o['M+']>9 ? o['M+'] : ('0'+o['M+']);
    o['d+'] = o['d+']>9 ? o['d+'] : ('0'+o['d+']);
    o['h+'] = o['h+']>9 ? o['h+'] : ('0'+o['h+']);
    o['m+'] = o['m+']>9 ? o['m+'] : ('0'+o['m+']);
    o['s+'] = o['s+']>9 ? o['s+'] : ('0'+o['s+']);

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

19.將json轉換成對象

function jsondecode(data){ 
    return (new Function("return "+data ))(); 
}

20.JS判斷訪問設備(userAgent)加載不同頁面。代碼如下:

function detectOS() {
    var sUserAgent = navigator.userAgent;

    var isWin = (navigator.platform === "Win32") || (navigator.platform === "Windows");
    var isMac = (navigator.platform === "Mac68K") || (navigator.platform === "MacPPC") || (navigator.platform === "Macintosh") || (navigator.platform === "MacIntel");
    var bIsIpad = sUserAgent.match(/ipad/i) === "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) === "iphone os";
    var isUnix = (navigator.platform === "X11") && !isWin && !isMac;
    var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
    var bIsAndroid = sUserAgent.toLowerCase().match(/android/i) === "android";
    var bIsCE = sUserAgent.match(/windows ce/i) === "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) === "windows mobile";
    if (isMac)
        return "Mac";
    if (isUnix)
        return "Unix";
    if (isLinux) {
        if (bIsAndroid)
            return "Android";
        else
            return "Linux";
    }
    if(bIsCE || bIsWM){
        return 'wm';
    }

    if (isWin) {
        var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
        if (isWin2K)
            return "Win2000";
        var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 ||
                sUserAgent.indexOf("Windows XP") > -1;
        if (isWinXP)
            return "WinXP";
        var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
        if (isWin2003)
            return "Win2003";
        var isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
        if (isWinVista)
            return "WinVista";
        var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
        if (isWin7)
            return "Win7";
        var isWin8 = sUserAgent.indexOf("Windows NT 6.2") > -1 || sUserAgent.indexOf("Windows 8") > -1;
        if (isWin8)
            return "Win8";
    }
    return "other";
}

21

/**
 * [formDataFun 將form數組數據轉換成對象數據]
 * @param  {[type]} formValue [數組數據]
 * @return {[type]}           [description]
 */
function formDataFun(formValue){
    var formData = {};
    for(var i=0,len=formValue.length; i

22.倒計時對象

//用法 var cd = new countDown(); cd.start(60,function(s){//s為剩下的秒數...}, function(){})
var countDown = function(){
    if(!(this instanceof countDown)){
        return  new countDown();
    }
    this.startD;
    this.interval;
    this.total;
    this.isStop = false;
};
//開始倒計時second:秒數,fresh:刷新顯示的倒計時時間
countDown.prototype.start = function(second, fresh, callback){
    var self = this;
    fresh && fresh(second);
//  setTimeout(function(){
        if(self.isStop){
            return;
        }
        self.total = second*1000;
        self.startD = new Date();
        self.interval = setInterval(function() {
            var nd = new Date();
            var ds = nd - self.startD - 100;
            if (ds > self.total) {
                clearInterval(self.interval);
                callback && callback();
            } else {
                fresh && fresh(Math.round((self.total - ds) / 1000));
            }
        }, 100); 
//  }, 1000);
};
//結束倒計時
countDown.prototype.stop = function(callback){
    var self = this;
    self.isStop = true;
    callback && callback();
    clearInterval(self.interval);
};

$(function(){

/**
 * outerHTML
 */
if(!document.body.outerHTML && window.HTMLElement) { 
    HTMLElement.prototype.__defineGetter__("outerHTML",function(){ //獲取

     var attr; 

        var attrs=this.attributes; 

        var str="<"+this.tagName.toLowerCase(); 

        for(var i=0;i= 0 ){
        $(".navigation-tabs2 li").addClass("xp-ie8-navli");
    }

});

發佈留言