前端常用代码段

版权声明:本文为博主(风轻云淡)原创文章,未经博主允许不得转载。CSDN https://blog.csdn.net/qq_20343517/article/details/82499148

以下是本人在实际项目开发中常用到的一些代码段

1、获取设备类型

var browser={
  versions:function(){
    var u = navigator.userAgent,
      app = navigator.appVersion;
    return {
      trident: u.indexOf('Trident') > -1, //IE内核
      presto: u.indexOf('Presto') > -1, //opera内核
      webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
      iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1, //是否iPad
      webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部
      weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增)
      qq: u.match(/\sQQ/i) == " qq",    //是否QQ
    };
  }(),
  language:(navigator.browserLanguage || navigator.language).toLowerCase()
};

2、获取URL参数

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

3、格式化时间

function  dataTime(str,time){
    var date=new Date(time);
    var o = {
        "o+" : date.getMonth()+1,                 //月
        "d+" : date.getDate(),                    //日
        "h+" : date.getHours(),                   //时
        "m+" : date.getMinutes(),                 //分
        "s+" : date.getSeconds(),                 //秒
    };
    if(/(y+)/.test(str))
        str=str.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(str))
            str = str.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return str;
}

4、复制到粘贴板

function copyToClipboard(text){
    if(text.indexOf('-') !== -1) {
        var arr = text.split('-');
        text = arr[0] + arr[1];
    }
    var textArea = document.createElement("textarea");
    textArea.style.position = 'fixed';
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.width = '2em';
    textArea.style.height = '2em';
    textArea.style.padding = '0';
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';
    textArea.style.background = 'transparent';
    // textArea.innerHTML=text;
    textArea.value=text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        var successful = document.execCommand('copy');
        var msg = successful ? '成功复制到剪贴板' : '该浏览器不支持点击复制到剪贴板';
        humane.log(msg, { timeout: 3000, clickToClose: true, addnCls: 'humane' });
    } catch (err) {
        humane.log('该浏览器不支持点击复制到剪贴板', { timeout: 3000, clickToClose: true, addnCls: 'humane' });
    }
    document.body.removeChild(textArea);
}

5、去除字符串首位空格

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

6、获取cookie

function getCookie(name){
    var cookie = document.cookie;       //获取cookie字符串
    var cookie = cookie.split("; ");    //分割
    //遍历匹配
    for ( var i = 0; i < cookie.length; i++) {
        var arr = cookie[i].split("=");
        if (arr[0] == name){
            return arr[1];
        }
    }
    return "";
}

7、过滤html标签

function removeHTMLTag(str) {
   str = str.replace(/<\/?[^>]*>/g,''); //去除HTML tag
   str = str.replace(/[ | ]*\n/g,'\n'); //去除行尾空白
   str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
   str=str.replace(/ /ig,'');//去掉
   return str;
},

8、ajax请求

function ajax(options){
    var xhr = null;
    var params = formsParams(options.data);
    //创建对象
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest()
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    // 连接
    if(options.type == "GET"){
        xhr.open(options.type,options.url + "?"+ params,options.async);
        xhr.send(null)
    } else if(options.type == "POST"){
        xhr.open(options.type,options.url,options.async);
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send(params);
    }
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            options.success(xhr.responseText);
        }
    }
    function formsParams(data){
        var arr = [];
        for(var prop in data){
            arr.push(prop + "=" + data[prop]);
        }
        return arr.join("&");
    }
 
}
 
ajax({
    url : "a.php",  // url---->地址
    type : "POST",   // type ---> 请求方式
    async : true,   // async----> 同步:false,异步:true 
    data : {        //传入信息
        name : "张三",
        age : 18
    },
    success : function(data){   //返回接受信息
        console.log(data);
    }
})

如果有其他的还会在补充

猜你喜欢

转载自blog.csdn.net/qq_20343517/article/details/82499148