美文网首页
JS常见通用方法总结

JS常见通用方法总结

作者: 小碗吃不了 | 来源:发表于2019-10-30 17:53 被阅读0次

    获取上传图片宽高

     <input
          type="file"
          accept="image/*"
          multiple     
          @change="getPicture($event)"
       > //  multiple 允许选择多个值
    
    getPicture: function (e) {
        //获取上传图片宽高
        var file = e.target.files;
        var ImgSize = [];
        for(var n = 0; n<file.length; n++){
          let imgSrc = window.URL.createObjectURL(file[n]);
          let img = new Image();
          img.src=imgSrc;
          img.onload = function(){
              ImgSize.push({w:img.width,h:img.height});
          }
        }
    }
    

    判断发布帖子距现在的时间

    function GetDateDiff(date) {
      if (date) {
          return date.replace(/\-/g, "/");
        }
    };
    //特殊时间格式转换正常格式 如2019-11-07T07:02:27.000+0000,IOS不兼容,最后后台转
    function renderTime(date) {
        var time= new Date(date).toJSON();
        return new Date(+new Date(time) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    }
    function filtDate(val) {
      var today = new Date().getTime();
      if(val.indexOf("T") != -1){
          val = renderTime(val)
      }
      var oldTime = new Date(GetDateDiff(val)).getTime();
      var limit = today - oldTime;
      var content = "";
      if (limit < 60000) {
        content = "刚刚";
      } else if (limit >= 60000 && limit < 3600000) {
        content = Math.floor(limit / 60000) + "分钟前";
      } else if (limit >= 3600000 && limit < 86400000) {
        content = Math.floor(limit / 3600000) + "小时前";
      } else if (limit >= 86400 && limit < 172800000) {
        content = "昨天";
      } else if (limit >= 172800000 && limit < 2592000000) {
        content = Math.floor(limit / 86400000) + "天前";
      } else if (limit >= 2592000000 && limit < 31104000000) {
        content = Math.floor(limit / 2592000000) + "个月前";
      } else {
        content = "很久前";
      }
        return content;
    }
    

    电话过滤器,中间4位*

    function filtPhone(tel) {
      if (tel) {
        tel = tel.split("");
        tel.splice(3, 4, "****");
        return tel.join("");
      } else {
        return ""
      }
    }
    

    获取当前时间(年月日),格式YYYY-MM-DD

    function getNowFormatDate() {
      var date = new Date();
      var seperator = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = year + seperator + month + seperator + strDate;
      return currentdate;
    }
    

    获取当前时间(年月日时分秒),格式YYYY-MM-DD hh:mm:ss

    function getNowFormatDateTime() {
      var date = new Date();
      var seperator1 = "-";
      var seperator2 = ":";
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
            " " + date.getHours() + seperator2 + date.getMinutes() + seperator2 + date.getSeconds();
      return currentdate;
    }
    

    判断对象内每个值是否为空,空返回false

    function isObjNull(obj) {
      if (obj) {
        if (JSON.stringify(obj) == "{}") {
          return false
        } else {
        for (let key in obj) {
          if (!obj[key]) {
            return false
          }
        }
      }
        return true
    } else {
        return false
      }
    }
    

    查询时间间隔天数(用于时间间隔限制)

      时间格式需为:2020-05-01 00:00:00
    
    
      var startTime = new Date(
          Date.parse(params.getTime[0].replace(/-/g, "/"))
        ).getTime();
        var endTime = new Date(
          Date.parse(params.getTime[1].replace(/-/g, "/"))
        ).getTime();
        var dates = Math.abs(startTime - endTime) / (1000 * 60 * 60 * 24);
        if (dates > 3) {
          this.$message({
            type: "warning",
            message: "查询间隔不超过三天"
          });
          return;
        }
    

    查询指定(当前日期)往后一周

        var today=new Date();
        var dateArr=[]
        for(var i=0;i<7;i++){
            var newDate=new Date(today.getTime()+i*1000*60*60*24)
            var year=newDate.getFullYear()
            var month=(parseInt(newDate.getMonth())+1)>9?(parseInt(newDate.getMonth())+1):"0"+(parseInt(newDate.getMonth())+1)
            var day=(newDate.getDate())>9?newDate.getDate():"0"+newDate.getDate()
            var fullDate=`${year}-${month}-${day}`
            dateArr.push(fullDate)
        }
        console.log(dateArr)
    

    比较时间大小

      时间格式需为:2020-05-01 00:00:00
     compareDate(d1, d2) {
      let reg = new RegExp("-", "g");
      return new Date(d1.replace(reg, "/")) > new Date(d2.replace(reg, "/"));
    },
    
    查最近几天(用于echarts图最近七天或一个月时间)
     // 最近七天
    getBeforeDate(n) {
      var n = n;
      // console.log(n);
      var d = new Date();
      var year = d.getFullYear();
      var mon = d.getMonth() + 1;
      var day = d.getDate();
      if (day <= n) {
        if (mon > 1) {
          mon = mon - 1;
        } else {
          year = year - 1;
          mon = 12;
        }
      }
      d.setDate(d.getDate() + n); //很重要,+n取得是前一天的时间
      year = d.getFullYear();
      mon = d.getMonth() + 1;
      day = d.getDate();
      var s = (mon < 10 ? "0" + mon : mon) + "-" + (day < 10 ? "0" + day : day);
      return s;
    },
    
    引用示例
    判断值是否为空
    validatenull(val) {
    if (typeof val == 'boolean') {
        return false;
    }
    if (typeof val == 'number') {
        return false;
    }
    if (val instanceof Array) {
        if (val.length == 0) return true;
    } else if (val instanceof Object) {
        if (JSON.stringify(val) === '{}') return true;
    } else {
        if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
        return false;
    }
      return false;
    }
    
    判断是否为整数
    export function validatenum(num) {
    let regName = /[^\d.]/g;
    if (!regName.test(num)) {
       return false;
    } else {
       return true;
      }
    }
    
    判断是否为小数
    export function validatenumord(num) {
    let regName = /[^\d.]/g;
        if (!regName.test(num)) return false;
        else  return true;
    }
    
    判断设备 验证pad还是pc
    export const vaildatePc = function () {
    const userAgentInfo = navigator.userAgent;
    const Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"
    ];
    let flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
    }
    
    判断URL地址
    export function isURL(s) {
       return /^http[s]?:\/\/.*/.test(s)
    }
    
    判断身份证号码
    export function cardid(code) {
    let list = [];
    let result = true;
    let msg = '';
    var city = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江 ",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北 ",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏 ",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
        91: "国外 "
    };
    if (!validatenull(code)) {
        if (code.length == 18) {
            if (!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) {
                msg = "证件号码格式错误";
            } else if (!city[code.substr(0, 2)]) {
                msg = "地址编码错误";
            } else {
                //18位身份证需要验证最后一位校验位
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2, 'x'];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                if (parity[sum % 11] != code[17]) {
                    msg = "证件号码校验位错误";
                } else {
                    result = false;
                }
    
            }
        } else {
            msg = "证件号码长度不为18位";
        }
    
    } else {
        msg = "证件号码不能为空";
    }
    list.push(result);
    list.push(msg);
    return list;
    }
    
    根据字典的value查找对应的index
    export const findArray = (dic, value) => {
    for (let i = 0; i < dic.length; i++) {
        if (dic[i].value == value) {
            return i;
        }
    }
    return -1;
    };
    // dic 为对象
    
    根据字典的value显示label
    // validatenull判空方法
    export const findByvalue = (dic, value) => {
    let result = '';
    if (validatenull(dic)) return value;
    if (typeof (value) == 'string' || typeof (value) == 'number' || typeof (value) == 'boolean') {
        let index = 0;
        index = findArray(dic, value);
        if (index != -1) {
            result = dic[index].label;
        } else {
            result = value;
        }
    } else if (value instanceof Array) {
        result = [];
        let index = 0;
        value.forEach(ele => {
            index = findArray(dic, ele);
            if (index != -1) {
                result.push(dic[index].label);
            } else {
                result.push(value);
            }
        });
        result = result.toString();
    }
    return result;
    };
    
    判断路由是否相等
    export const diff = (obj1, obj2) => {
    delete obj1.close;
    var o1 = obj1 instanceof Object;
    var o2 = obj2 instanceof Object;
    if (!o1 || !o2) { /*  判断不是对象  */
        return obj1 === obj2;
    }
    
    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
        return false;
        //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组
        //例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
    }
    
    for (var attr in obj1) {
        var t1 = obj1[attr] instanceof Object;
        var t2 = obj2[attr] instanceof Object;
        if (t1 && t2) {
            return diff(obj1[attr], obj2[attr]);
        } else if (obj1[attr] !== obj2[attr]) {
            return false;
        }
    }
    return true;
    }
    
    动态插入css
    export const loadStyle = url => {
      const link = document.createElement('link');
      link.type = 'text/css';
      link.rel = 'stylesheet';
      link.href = url;
      const head = document.getElementsByTagName('head')[0];
      head.appendChild(link);
    };
    
    浏览器全屏
    export const reqFullScreen = () => {
    if (document.documentElement.requestFullScreen) {
        document.documentElement.requestFullScreen();
    } else if (document.documentElement.webkitRequestFullScreen) {
        document.documentElement.webkitRequestFullScreen();
    } else if (document.documentElement.mozRequestFullScreen) {
        document.documentElement.mozRequestFullScreen();
    }
    };
    
    浏览器退出全屏
    export const exitFullScreen = () => {
    if (document.documentElement.requestFullScreen) {
        document.exitFullScreen();
    } else if (document.documentElement.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
    } else if (document.documentElement.mozRequestFullScreen) {
        document.mozCancelFullScreen();
    }
    };
    
    倒计时60秒重新获取验证码(接入网易易盾,图形验证)
    <van-popup v-model="showPopup" safe-area-inset-bottom duration="0.3" position="center" lock-scroll lazy-render
            round close-on-popstate :close-on-click-overlay="false" :style="{height: '61vw',width:'68%' }">
            <h3 style="margin-bottom: 15px">登录</h3>
            <input type="tel" maxlength="11" placeholder="请输入手机号" v-model="phone">
            <div class="code-box">
                <input type="tel" maxlength="11" id="code" class="c_code" v-model="code" placeholder="请输入验证码">
                <input type="button" v-model="count" class="c_code-button" id="btnSendCode1" @click="getCodes"
                    :disabled="disabled"></input>
            </div>
            <button type="button" class="login_con" @click="login">确认</button>
        </van-popup>
    动态引入易盾 加时间戳
      <script>
        var url = 'https://cstaticdun.126.net/load.min.js' + '?t=' + (new Date()).getTime()
        document.writeln('<script src="' + url + '">' + '</' + 'script>');
      </script>
    
    data() {
        return {
            allCount:60,
            phone:"",
            code:"",
            captchaIns :""//易盾实例
        }
    }
    created: function () {
        this.getInter();//初始化易盾
    },
    methods: {
         // 易盾
         getInter() {
              let that = this;
                    initNECaptcha({
                        element: '#captcha',
                        captchaId: '5fd47b149907473182065fedc5f243fa',
                        mode: 'popup',
                        width: '220px',
                        protocol: 'https',
                        onClose: function () {
                        },
                        onVerify: function (err, res) {
                            if (res) {
                                that.getbikeAsyncAjaxApi2('mego-user/wxUser/wyVerify', 'post', {
                                    mobile: that.phone.trim(),
                                    validate: res.validate
                                }, (data) => {
                                    //设置button效果,开始计时
                                    that.disabled = true
                                    that.count = that.curCount1 + "秒再获取"
                                    that.InterValObj1 = setInterval(that.SetRemainTime1, 1000); //启动计时器,1秒执行一次
                                    vant.Toast.success('发送成功')
                                })
                            }
                        }
                    }, function (instance) {
                        that.captchaIns = instance;
                    }, function (err) {
                        // 初始化失败后触发该函数,err对象描述当前错误信息
                    })
                },
        //倒计时60
        SetRemainTime: function () {
             if (this.allCount == 0) {
                    this.disabled = false //必须为input
                    clearInterval(this.InterValObj1); //停止计时器
                    this.count = "重新发送";
             } else {
                    this.allCount= this.allCount- 1;
                    this.count = this.allCount+ "秒再获取"
                }
            },
             // 验证码时间
                getCodes() {
                    if (!this.phone.trim()) return vant.Toast('请输入手机号');
                    if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.phone.trim())) return vant.Toast('手机号格式错误');
                    //调取易盾前刷新
                    this.captchaIns && this.captchaIns.refresh()
                    this.captchaIns && this.captchaIns.popUp()
                },
    }
    
    获取当前网址内传参值(以对象形式返回)
     getQueryString: function () {
          var theRequest = {}
          var r = window.location.search;
          if (r.indexOf("?") != -1) {
                var str = r.substr(1);
                 str = str.replace("?", "&");
                 strs = str.split("&");
                 for (var i = 0; i < strs.length; i++) {
                      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                  }
             }
           return theRequest;
          }
    
    获取当前时间或指定开始时间至指定结束时间的秒数(用于活动开奖后至结束倒计时)
      this.endtime = '2020-08-10 14:50:00' //示例
      getM() {
        let date = new Date()
        let now = date.getTime()
         // let now = new Date(this.nowtime.replace(/-/g, '/'))   
         let endDate = new Date(this.endtime.replace(/-/g, '/'))   //兼容ios
         let end = endDate.getTime(); 
         let leftTime = end - now;
         if (leftTime > 0) {
               let d =  Math.floor(leftTime / 1000 / 60 / 60 / 24);
               let h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
               let m = Math.floor(leftTime / 1000 / 60 % 60)
               let s = Math.floor(leftTime / 1000 % 60)
               this.totalTime = s + m * 60 + h * 60 * 60 + d * 24 * 60 * 60;
               console.log(this.totalTime)
          }
     }
    
    活动开始倒计时
     this.startime = '2020-08-10 14:50:00' //示例
    
    根据判断条件开启活动倒计时定时
    this.isCountTime = setInterval(this.countTime, 1000)
    
     countTime() {
          let that = this;
          let date = new Date()
          let now = date.getTime()
          let endDate = new Date(this.startime.replace(/-/g, '/'))
          let end = endDate.getTime();
          let leftTime = end - now;
          if (leftTime > 0) {
              this.day = Math.floor(leftTime / 1000 / 60 / 60 / 24)
              let h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
              this.hour = h < 10 ? '0' + h : h
              let m = Math.floor(leftTime / 1000 / 60 % 60)
              this.min = m < 10 ? '0' + m : m
              let s = Math.floor(leftTime / 1000 % 60)
              this.second = s < 10 ? '0' + s : s;
              console.log("剩下时间-" + this.hour + ':' + this.min + ':' + this.second)
           } else {
              window.clearInterval(this.isCountTime);
               //此处用于启动开奖至结束倒计时
          }
        },
    
    判断当前时间是否存在两个时间之内
      //时间格式  2020-08-06 16:50:00
     isDuringDate(beginDateStr, endDateStr) {
         var curDate = new Date(),
         beginDate = new Date(beginDateStr),
         endDate = new Date(endDateStr);
         if (curDate >= beginDate && curDate <= endDate) {
                 return true;
          }
           return false;
      },
    
    判断pc还是手机端加载不同地址
    if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
             // window.location.href = "http://127.0.0.1:8848/web-mego/web-phone/index.html"
             console.log("移动端")
             window.location.href = "https://m.megobike.com/"
     }else{
            // window.location.href = "http://127.0.0.1:8848/web-mego/megobike-web/index.html"
            window.location.href = "http://www.megobike.com";
    }
    

    相关文章

      网友评论

          本文标题:JS常见通用方法总结

          本文链接:https://www.haomeiwen.com/subject/lqihvctx.html