字符串
/**
* 下划线转换驼峰
* 参数string类型字符串
* 返回字符串
*/
export const stringToHump = (string: String) => {
if (string === null || string === '') {
return string;
}
return string.replace(/\_(\w)/g, letter => letter.toUpperCase());
};
/**
* 驼峰转换下划线
* 参数string类型字符串
* 返回字符串
*/
export const stringToLine = (string: String) => {
if (string === null || string === '') {
return string;
}
return string.replace(/([A-Z])/g, '_$1').toLowerCase();
};
/**
* 首字母大写
* 参数string类型字符串
* 返回字符串
*/
export const stringToCase = (string: String) => {
if (string === null || string === '') {
return string;
}
return string.replace(/\b\w+\b/g, word => {
return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
});
};
/**
* 多少个字符后加省略号
* 参数string类型字符串
* 参数number类型数字
* 返回字符串
*/
export const stringToEllipsis = (string: String, num: Number) => {
if (string === null || string === '') {
return string;
}
if (string.length > num) {
return `${string.substring(0, Number(num) - 1)}...`;
}
return string;
};
/**
* 手机号中间四位隐藏****
* 参数string类型字符串
* 返回字符串
*/
export const stringToHideNumber = (string: String) => {
if (string === null || string === ''|| string?.length !== 11) {
return string;
}
const reg = /^(\d{3})\d{4}(\d{4})$/;
string = string.replace(reg, '$1****$2');
return string;
};
通用组件
/**
* 组织冒泡
*/
export function stopBubble(e: Event) {
if (e && e.stopPropagation) {
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}
}
/**
* 防抖函数
*/
export function debounce(func: any, wait: number) {
let timeout = null
return function () {
clearTimeout(timeout)
timeout = setTimeout(() => {
func.apply(this, arguments)
}, wait)
}
}
/**
* 节流函数
*/
export function throttle(func: any, wait: number) {
let previous = 0
return function () {
let now = +new Date()
let remain = wait - (now - previous)
if (remain < 0) {
previous = now
func.call(this, arguments)
}
}
}
/**
* 数据类型判断
*/
export function judgeDataType(obj: any) {
return typeof obj === 'object'
? Object.prototype.toString.call(obj).replace('[object ', '').replace(']', '').toLowerCase()
: typeof obj;
}
/**
* 深拷贝
*/
export function clone(any: any) {
function checkType(any) {
return Object.prototype.toString.call(any).slice(8, -1)
}
if (checkType(any) === 'Object') { // 拷贝对象
let o = {};
for (let key in any) {
o[key] = clone(any[key])
}
return o;
} else if (checkType(any) === 'Array') { // 拷贝数组
var arr = []
for (let i = 0, leng = any.length; i < leng; i++) {
arr[i] = clone(any[i])
}
return arr;
} else if (checkType(any) === 'Function') { // 拷贝函数
return new Function('return ' + any.toString()).call(this)
} else if (checkType(any) === 'Date') { // 拷贝日期
return new Date(any.valueOf())
} else if (checkType(any) === 'RegExp') { // 拷贝正则
return new RegExp(any)
} else if (checkType(any) === 'Map') { // 拷贝Map 集合
let m = new Map()
any.forEach((v, k) => {
m.set(k, clone(v))
})
return m
} else if (checkType(any) === 'Set') { // 拷贝Set 集合
let s = new Set()
for (let val of any.values()) {
s.add(clone(val))
}
return s
}
return any;
}
浏览器
/**
* 滚动到页面顶部
* 无返回值
*/
export const scrollToTop =()=>{
const fromTop = document.documentElement.scrollTop || document.body.scrollTop;
if (fromTop > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, fromTop - fromTop/ 8);
}
}
/**
* 滚动到页面底部
* 无返回值
*
*/
//获取页面文档的总高度
function documentHeight(){
return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
}
export const scrollToBottom =()=>{
const fromTop = document.documentElement.scrollTop || document.body.scrollTop;
let max = documentHeight()
if (fromTop > 0) {
window.requestAnimationFrame(scrollToBottom);
window.scrollTo(0,max);
}
}
/**
* 滚动到页面任意位置
* xpos 滚动位置的横坐标
* ypos 滚动位置的纵坐标
*/
export const scrollToAny =(xpos,ypos)=>{
window.scrollTo(xpos,ypos);
}
/**
* 获取可视页面宽度
* 返回number类型
*/
export const getViewPortWidth =()=>{
return document.documentElement.clientWidth || document.body.clientWidth;
}
/**
* 获取可视页面高度
* 返回number类型
*/
export const getViewPortHeight =()=>{
return document.documentElement.clientHeight || document.body.clientHeight;
}
/**
* 打开浏览器全屏
* 无返回值
*/
export const openFullScreen = ()=>{
let docElm = document.documentElement;
if (docElm.requestFullscreen) {
docElm.requestFullscreen();
}
}
/**
* 退出浏览器全屏
* 无返回值
*/
export const exitFullScreen = ()=> {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
/**
* 文本复制
* 无返回值
*/
//已经选中p/span等标签的文本,需要复制选中文本
export const copyselectTxt = () => {
document.execCommand("Copy"); // 把已选文本复制
}
//实现点击按钮,复制文本框中的的内容
export const copyUrl = () => {
let url = document.querySelector('input');
url.select(); // 选择对象
document.execCommand('Copy'); // 执行浏览器复制命令
alert("已复制好,可贴粘。");
}
//没选中,但想要复制指定元素的文本。
export const copyTxt = ()=> {
let url = document.querySelector('input');
url.select(); // 选择对象
document.execCommand('Copy'); // 执行浏览器复制命令
alert("已复制好,可贴粘。");
}
日期、时间
/**
* @description 获取当前时间(年月日)
*/
export const getNowDate = () => {
let nowdate = new Date();
let y = nowdate.getFullYear();
let m = nowdate.getMonth() + 1;
let d = nowdate.getDate();
return y + "-" + m + "-" + d;
}
/**
* @description 获取当前时间(年月日时分秒)
*/
export const getDateTime = () => {
let d, s
d = new Date()
let addZero = value => { return value < 10 ? `0${value}` : value }
s = `${d.getFullYear()}-`
s = `${s}${addZero(d.getMonth() + 1)}-`
s += `${addZero(d.getDate())} `
s += `${addZero(d.getHours())}:`
s += `${addZero(d.getMinutes())}:`
s += `${addZero(d.getSeconds())}`
return s
}
/**
* @description 时间转换时间戳(标准时间=>时间戳)例如:'2020-03-12 18:00:00'
* @param {string} date 需要转换时间转换时间
* @return {string} 转换后的时间戳
*/
export const dateToTimestamp = (date) => {
return date.getTime();
}
/**
*
* @description 时间格式化
* @param {nuber} timestamp 当前时间戳,毫秒
* @param {string} formats 时间格式,包括:
* 1. Y-m-d
* 2. Y-m-d H:i:s
* 3. Y年m月d日
* 4. Y年m月d日 H时i分s秒
*/
export const dateFormat = (timestamp, formats) => {
formats = formats || 'Y-m-d';
let zero = v => v < 10 ? `0${v}` : v
let myDate = timestamp ? new Date(timestamp) : new Date();
let year = myDate.getFullYear();
let month = zero(myDate.getMonth() + 1);
let day = zero(myDate.getDate());
let hour = zero(myDate.getHours());
let minute = zero(myDate.getMinutes());
let second = zero(myDate.getSeconds());
return formats.replace(/Y|m|d|H|i|s/ig, matches => {
return ({
Y: year,
m: month,
d: day,
H: hour,
i: minute,
s: second
})[matches];
});
};
/**
*
* @description 提取年
* @param {number} timestamp 当前时间戳,毫秒
*/
export const dateY = timestamp => {
let newDate = new Date(timestamp);
let { y } = { y: newDate.getFullYear() };
return `${y}`;
}
/**
*
* @description 提取年月
* @param {number} timestamp 当前时间戳,毫秒
*/
export const dateYM = timestamp => {
let newDate = new Date(timestamp);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return `${y}-${m}`;
}
/**
*
* @description 提取年月日
* @param {number} timestamp 当前时间戳,毫秒
*/
export const dateYMD = timestamp => {
let newDate = new Date(timestamp);
let { y, m, d } = { y: newDate.getFullYear(), m: newDate.getMonth() + 1, d: newDate.getDate() };
return `${y}-${m}-${d}`;
}
/**
*
* @description 提取年月日时分秒
* @param {number} timestamp 当前时间戳,毫秒
*/
export const dateTime = timestamp => {
let newDate = new Date(timestamp);
let { y, M, d, h, m, s } = { y: newDate.getFullYear(), M: newDate.getMonth() + 1, d: newDate.getDate(), h: newDate.getHours(), m: newDate.getMinutes(), s: newDate.getSeconds() };
return `${y}-${M}-${d} ${h}:${m}:${s}`;
}
/**
*
* @description 计算多长时间以前
* @param {number} timestamp 当前时间戳,毫秒
*/
export const timeFilter = timestamp => {
timestamp -= 0;
let difTime = new Date().getTime() - timestamp;
let { h, m, s } = { h: parseInt(`${difTime / (3600 * 1000)}`), m: parseInt(`${difTime / (60 * 1000)}`), s: parseInt(`${difTime / 1000}`) };
let msg = "";
if (m < 1) {
msg = `${s}秒前`
} else if (m >= 1 && h < 1) {
msg = `${m}分钟前`;
} else if (h >= 1 && h <= 24) {
msg = `${h}小时前`;
} else if (h > 24) {
h = parseInt(`${h / 24}`)
msg = `${h}天前`;
}
return msg;
}
/**
*
* @description 字符替换
* @param {string} str 被处理字符串
* @param {string}l 被替换字符
* @param {string} r 替换字符
*/
export const transFormat = (str, l, r) => {
let reg = new RegExp(l, 'g') // g表示全部替换,默认替换第一个
str = str.replace(reg, r)
return str
}
/**
*
* @description 通过日期计算间隔时间
* @param {string} strDateStart 开始时间(YYYY-MM-DD)
* @param {string} strDateEnd 结束时间(YYYY-MM-DD)
*/
export const intervalDate = (strDateStart, strDateEnd) => {
let strSeparator = "-"; //日期分隔符
let oDate1;
let oDate2;
let iDays;
oDate1 = strDateStart.split(strSeparator);
oDate2 = strDateEnd.split(strSeparator);
let strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
let strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
iDays = parseInt(`${Math.abs(Number(strDateS) - Number(strDateE)) / 1000 / 60 / 60 / 24}`);//把相差的毫秒数转换为天数
return iDays;
}
/**
*
* @description 通过时间戳计算间隔时间
* @param {number} strDateStart 开始时间(时间戳-毫秒)
* @param {number} strDateEnd 结束时间(时间戳-毫秒)
*/
export const intervalTimeStamp = (startTime, endTime) => {
let stime = new Date(startTime).getTime();
let etime = new Date(endTime).getTime();
let intervalTime = etime - stime;
let intervalDay = Math.floor(intervalTime / (24 * 3600 * 1000));
let interval = intervalDay;
return interval;
}