js中好用的方法(复制剪贴板、时间转换、大数字单位转换)
复制内容到手机剪贴板:
/**
* 拷贝数据到剪贴板
*/
public static CopyToClipBoard(str){
let copyDom = document.createElement("input");
// 获得需要复制的内容
copyDom.setAttribute("value",str);
//不需要让他displaynone
// copyDom.style.display = "none";
// 添加到 DOM 元素中
document.body.appendChild(copyDom);
// 注意: 只有 input 和 textarea 可以执行 select() 方法.
copyDom.select();
// 获得选中的内容
let content = window.getSelection().toString();
// 执行复制命令
document.execCommand("copy");
// 将 input 元素移除
document.body.removeChild(copyDom);
console.log("复制成功:"+ str);
}
大数值单位制转换:
/**
* 大数值单位制转换
* @param num 数值
*/
public static largeNumToString(num: number) {
if (num < 10000)
return "" + num;
else if (num >= 100000000) {
let mod = num % 100000000;
if (mod) {
if (mod < 10000)
return (num - mod) / 100000000 + "亿";
return (num - mod) / 100000000 + "亿" + (mod / 10000 | 0) + "万";
}
return num / 100000000 + "亿";
} else {
let mod = num % 10000;
if (mod)
return (num - mod) / 10000 + "万";
return num / 10000 + "万";
}
}
时间转换:
/**
* 毫秒转换为天数/00:00:00
* @param ms
*/
public static timeToTimeString(ms: number){
ms = Math.round(ms / 1000);
let day = Math.floor(ms / (3600 * 24)) | 0,
h = Math.floor(ms / 3600) % 24 | 0,
m = Math.floor(ms / 60) % 60 | 0,
s = ms % 60;
if (day > 0)
return (day < 10 ? ("00" + day).slice(-2) : day) + "天" + ("00" + h).slice(-2) + "小时";
return ("00" + h).slice(-2) + ":" + ("00" + m).slice(-2) + ":" + ("00" + s).slice(-2);
}
/**
* 时间转换为天数
* @param time
*/
public static timeToDays(time: number): number {
let date = new Date(time * 1000);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
if (time == 0)
return 0;
return Math.ceil((Util.getCurTimeStamp() - date.getTime()) / (1000 * 60 * 60 * 24));
}
/**
* 时间转为00:00:00
* @param time
*/
public static getTimeToString(time: number) {
let text, hour, min, sec;
hour = Math.floor(time / (60 * 60));
min = Math.floor(time / 60) % 60;
sec = time % 60;
text = (hour > 9 ? hour : "0" + hour) + ":" + (min > 9 ? min : "0" + min) + ":" + (sec > 9 ? sec : "0" + sec);
return text;
}
/**
* 毫秒时间转为00:00:00
* @param time
*/
public static msToTimeString(ms: number) {
ms = Math.round(ms / 1000);
let h = ms / 3600 | 0,
m = (ms - h * 3600) / 60 | 0,
s = ms % 60,
text = ("00" + h).slice(-2) + ":" + ("00" + m).slice(-2) + ":" + ("00" + s).slice(-2);
return text;
}
```