js-utils-v1
Version:
一组常用的 JavaScript 工具函数,包含时间格式化、图片下载、节流防抖等。
92 lines (85 loc) • 2.62 kB
JavaScript
// 处理日期
export const formatTime = (dateString, M = null) => {
const date = new Date(dateString);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
if (M === "month") return `${month}-${day}`;
if (M === "time") return `${hours}:${minutes}`;
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 下载图片
export const Download = (url) => {
if (!url || url.toLowerCase().endsWith(".gif")) {
throw new Error("暂无图片可下载");
}
const link = document.createElement("a");
link.href = url;
link.download = "bimoai.png";
link.style.display = "none";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
// 节流
export const throttle = (func, delay) => {
let timeoutId = null;
return function (...args) {
if (!timeoutId) {
func.apply(this, args).finally(() => {
timeoutId = setTimeout(() => {
timeoutId = null;
}, delay);
});
}
};
};
// 防抖
export const debounce = (func, wait, immediate) => {
let timeout;
return function (...args) {
const context = this;
const later = () => {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// 处理成Base64
export const urlToBase64 = async (url) => {
try {
const response = await fetch(url, { cache: "no-store" });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
} catch (error) {
console.error("Failed to fetch:", error);
throw error;
}
};
// 图片大小限制
export const validateFile = (file, size) => {
const allowedTypes = ["image/jpeg", "image/png"];
const maxSize = size * 1024 * 1024;
if (!allowedTypes.includes(file.type)) {
throw new Error("仅支持 JPG 和 PNG 格式的图片!");
}
if (file.size > maxSize) {
throw new Error("文件大小不能超过" + size + "MB!!");
}
return true;
};