Skip to content

Instantly share code, notes, and snippets.

@hipi
Last active June 28, 2021 03:26
Show Gist options
  • Save hipi/2c9b7187264f838cc1bb5048c70c32f9 to your computer and use it in GitHub Desktop.
Save hipi/2c9b7187264f838cc1bb5048c70c32f9 to your computer and use it in GitHub Desktop.
常用的工具函数
// 打印颜色字体
const logColor = (text,color="#ffb3cc") => {
console.log("%c " + text, "color: " + color + "; font-weight: bold;")
}
// 随机获取颜色
const getRandomColor = ()=> {
let rgb = []
for (let i = 0; i < 3; ++i) {
let color = Math.floor(Math.random() * 256).toString(16)
color = color.length == 1 ? '0' + color : color
rgb.push(color)
}
return '#' + rgb.join('')
}
// 判断元素是否可见
const isElementInViewport = (el) => {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
// 获取老时间字符
function getOldTimeStr(time) {
if (!time) {
return "";
}
let oldTimestamp = time;
if ("string" === typeof time) {
oldTimestamp =
new Date(time).getTime() || new Date(time.replace(/-/g, "/")).getTime();
}
var todayStartTimestamp = new Date(new Date().toLocaleDateString()).getTime();
const differTimestamp = Date.now() - oldTimestamp;
console.log("🚀 ~ olde ~ differTimestamp", differTimestamp);
if (differTimestamp < 6e4) {
return "刚刚";
}
if (differTimestamp < 36e5) {
return Math.floor(differTimestamp / 6e4) + "分钟前";
}
if (differTimestamp < 864e5) {
return oldTimestamp >= todayStartTimestamp
? Math.floor(differTimestamp / 36e5) + "小时前"
: "昨天";
}
if (differTimestamp < 1728e5) {
return oldTimestamp >= todayStartTimestamp - 864e5 ? "昨天" : "前天";
}
if (
differTimestamp < 2592e5 &&
oldTimestamp >= todayStartTimestamp - 1728e5
) {
return "前天";
}
const oldTime = new Date(oldTimestamp);
const oldYear = oldTime.getFullYear();
let oldTimeStr = `${oldTime.getMonth() + 1}.${oldTime.getDate()}`;
if (new Date().getFullYear() !== oldYear) {
oldTimeStr = `${oldYear}.${oldTimeStr}`;
}
return oldTimeStr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment