常用js

1.转中文编码

function mspGb2312(key)
{
    var r = "";
    for(var i=0;ivar t = key.charCodeAt(i);
        if(t>=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:包含切换图片的div的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+" .imgsdiv .curimg"),nextObj=$("#"+imgDivId+" .imgsdiv .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; iif(formValue[i].value){
            formData[formValue[i].name] = formValue[i].value;
        }
    }
    return formData;
}

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;iif(attr.specified) 

                str+=" "+attr.name+'="'+attr.value+'"'; 

            } 

        return str+">"+this.innerHTML+"+this.tagName.toLowerCase()+">"; 

    }); 

    HTMLElement.prototype.__defineSetter__("outerHTML",function(s) //设置

    { 

        var r = this.ownerDocument.createRange(); 

         r.setStartBefore(this); 

        var df = r.createContextualFragment(s); 

        this.parentNode.replaceChild(df, this); 

        return s; 

     }); 

}

    $(".logo").click(function(){
    //  location.href="index.php";
    });
  $(".auto_width").on("keyup",function(){
        var size = textWidth($(this).val());
        var thisObj = $(this);
        var maxHeight = parseInt(thisObj.css("max-height"));
        var maxWidth = parseInt(thisObj.css("max-width"));
        if(this.tagName.toUpperCase()=="TEXTAREA"){
            size[0] = size[0]+20;
        }
        if(maxHeight && maxHeight1]){
            thisObj.css({"overflow-y":"auto"});
        }
        if(maxWidth && maxWidth0]){
            thisObj.css({"overflow-x":"auto"});
        }
        $(this).width(size[0]); 
        $(this).height(size[1]); 
  })
  $(".auto_width").each(function(){
        var size = textWidth($(this).val());
        var thisObj = $(this);
        if(this.tagName.toUpperCase()=="TEXTAREA"){
            size[0] = size[0]+20;
        }
        $(this).width(size[0]); 
        $(this).height(size[1]); 
   });

  //input readonly
  $("body").on("keydown", ":text[readonly]", function(event){
        if(document.all){
          window.event.returnValue = false;
          window.event.cancelBubble = true;    
        }else{
          event.preventDefault();
          event.stopPropagation();
        }
        return false;
  });

  //补丁:xp ie8 .navigation-tabs2 li
    if("WinXP" == detectOS() && window.navigator.userAgent.indexOf("MSIE") >= 0 ){
        $(".navigation-tabs2 li").addClass("xp-ie8-navli");
    }

});

你可能感兴趣的:(js)