移动端开发常用snippets

时间:2022-03-05 18:38:44

  1. 判断浏览器环境
  2. 解析url参数
  3. 时间格式化

判断浏览器环境

const UA  = navigator.userAgent;

// 判断终端类型
const isWechatBrowser = () => {
    return /micromessenger/i.test(UA);
  };
const isMobile = () => {
    const regExp = /ipad|iphone|android|blackberry|windows phone|webos/i
    return regExp.test(UA)
}
const isIos = () => {
    return /iphone|ipad|ipod/i.test(UA)
}
const isiPhone = () => {
    return /iphone/i.test(UA)
}
const isIpad = () => {
    return /ipad/i.test(UA)
}
const isIpod = () => {
    return /ipod/i.test(UA)
}
const isAndroid = () => {
    return /android/i.test(UA)
}

/*判断浏览器类型*/
const isFirefox = () => {
    return /firefox/i.test(UA);
}
const isChrome = () => {
    return /chrome/i.test(UA)
}
exports {isWechatBrowser}

解析url参数

const urlQueryToObject = (url) => {
    const arr =  url.split('?')[1].split('&');
  return  arr.reduce((acc,value,index) => {value.replace(/(w )=(w )/,(match,p1,p2) => {acc[p1] = p2});return acc},{})
}
// exapmple
// location.href="http:example.com/index.html?a=1&b=2"
urlQueryToObject(location.href) // {a:1,b:2}

时间格式化

export const  createAt = date => {
    var time = new Date(date);
    var year = time.getFullYear();
    var month = time.getMonth()   1;
    var day = time.getDate();
    var hh = time.getHours();
    var mm = time.getMinutes();
    return year   '年'   month   '月'   day   '日'   ' '   hh   ':'   mm;
}
export const timeAgo  = (date) =>  {
    var seconds = Math.floor((new Date() - new Date(date)) / 1000);

    const yearseconds = 365 * 24 * 60 * 60;// 一年有多少秒
    const monthseconds = 30 * 24 * 60 * 60; //  一个月有多少秒
    const dateseconds = 24 * 60 * 60;// 一天有多少秒

    let interval = 0;

    if (seconds > yearseconds) {
        return createAt(date);
    } else if (seconds > monthseconds) {
        interval = Math.floor(seconds / monthseconds);
        return interval   '月前';
    } else if (seconds > dateseconds) {
        interval = Math.floor(seconds / dateseconds);
        return interval   '天前';
    } else if (seconds > 3600) {
        interval = Math.floor(seconds / 3600);
        return interval   '小时前';
    } else if (seconds > 60) {
        interval = Math.floor(seconds / 60);
        return interval   '分钟前';
    } else {
        return '刚刚';
    }
},

参考: