就本人平时所用的前端常用工具类方法记录一下,有需要的可以随时获取,且不定时更新,大家一起学习进步,主要按模块分类:
1.防抖
export function debounce(fn, delay) {
let timrs;
return function (...args) {
clearTimeout(timrs);
timrs = setTimeout(() => {
fn.apply(this, args);
}, delay);
}
}
2.图片篇
export function isImage(url) {
const fileType = url.slice(url.lastIndexOf('.') + 1);
return ['png', 'jpg', 'jpeg'].includes(fileType.toLowerCase());
}
3.样式篇
export function px2rem(px) {
if (/%/ig.test(px)) {
return px;
} else {
return (parseFloat(px) / 100) + 'rem'
}
}
4.页面内容
export function handleFullScreenEvent(el) {
const isFullscreen =
el.fullScreen || el.mozFullScreen || el.webkitIsFullScreen;
if (!isFullscreen) {
(el.requestFullscreen && el.requestFullscreen()) ||
(el.mozRequestFullScreen && el.mozRequestFullScreen()) ||
(el.webkitRequestFullscreen && el.webkitRequestFullscreen()) ||
(el.msRequestFullscreen && el.msRequestFullscreen());
}
}
export function getUrlParams(name) {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const searchPath = window.location.search.substring(1);
const hashPath = window.location.hash.split('?')[1];
let r = searchPath && searchPath.match(reg);
if (!r) {
r = hashPath && hashPath.match(reg);
}
if (r != null) return unescape(r[2]);
return null;
}
5.其他
export function randomString(length = 10, chars?) {
const defaultChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
chars = chars || defaultChars;
let result = "";
for (let i = length; i > 0; --i)
result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
export const flatArr = (arr) => {
return arr.reduce(
(acc, cur) => acc.concat(Array.isArray(cur) ? flatArr(cur) : cur),
[]
);
};
**
* 获取中文
* @param num
* @returns {*}
*/
function SectionToChinese(section) {
const ori = section;
let strIns = '';
let chnStr = '';
let unitPos = 0;
let zero = true;
while (section > 0) {
const v = section % 10;
if (v === 0) {
if (!zero) {
zero = true;
chnStr = chnNumChar[v] + chnStr;
}
} else {
zero = false;
strIns = chnNumChar[v];
strIns += chnUnitChar[unitPos];
chnStr = strIns + chnStr;
}
unitPos++;
section = Math.floor(section / 10);
}
if (ori < 20) {
chnStr = chnStr.replace('一十', '十');
}
return chnStr;
}
export function numberToChanie(num) {
let unitPos = 0;
let strIns = '',
chnStr = '';
let needZero = false;
if (num === 0) {
return chnNumChar[0];
}
while (num > 0) {
const section = num % 10000;
if (needZero) {
chnStr = chnNumChar[0] + chnStr;
}
strIns = SectionToChinese(section);
strIns += section !== 0 ? chnUnitSection[unitPos] : chnUnitSection[0];
chnStr = strIns + chnStr;
needZero = section < 1000 && section > 0;
num = Math.floor(num / 10000);
unitPos++;
}
return chnStr;
}
export const sleep = (delay = 2000) => new Promise((resolve) => setTimeout(resolve, delay));
export function pollTimer(fn, time, opt?) {
let timers: any = null;
if (timers) {
clearInterval(timers);
}
fn(true);
if (!opt?.once) {
timers = setInterval(fn, time);
}
return timers;
}
export function calcMettingTime(startTime, endTime) {
let str = '';
const times = (endTime - startTime) / 1000;
const hours = Math.floor(times / 3600);
const minutes = Math.floor((times % 3600) / 60);
const seconds = Math.floor((times % 3600) % 60);
str += `${hours < 10 ? '0' + hours : hours}:`;
str += `${minutes < 10 ? '0' + minutes : minutes}:${
seconds < 10 ? '0' + seconds : seconds
}`;
return str;
}
export function calcEventTime(startTime, endTime) {
const times = (endTime - startTime) / 1000;
const days = Math.floor(times / 86400);
const hours = Math.floor((times % 86400) / 3600);
const minutes = Math.floor((times % 3600) / 60);
const seconds = Math.floor((times % 3600) % 60);
return {
days: days < 10 ? `0${days}` : days,
hours: hours < 10 ? `0${hours}` : hours,
minutes: minutes < 10 ? `0${minutes}` : minutes,
seconds: seconds < 10 ? `0${seconds}` : seconds,
};
}
<input type="file" id="videoUpload" accept="video/*">
< img id="thumbnail" alt="视频封面" style="max-width: 300px; display: none;">
<script>
document.getElementById('videoUpload').addEventListener('change', async function(event) {
const file = event.target.files[0];
if (!file) return;
const video = document.createElement('video');
video.src = URL.createObjectURL(file);
video.crossOrigin = "anonymous";
video.muted = true;
video.autoplay = true;
video.playsInline = true;
video.addEventListener('loadeddata', async function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob(async function(blob) {
const thumbnailImg = document.getElementById('thumbnail');
thumbnailImg.src = URL.createObjectURL(blob);
thumbnailImg.style.display = 'block';
await uploadToCOS(blob, 'video-thumbnail.jpg');
await uploadToCOS(file, 'uploaded-video.mp4');
}, 'image/jpeg');
});
});
async function uploadToCOS(file, filename) {
const COS = new COS({
SecretId: "你的SecretId",
SecretKey: "你的SecretKey"
});
return new Promise((resolve, reject) => {
COS.putObject({
Bucket: "你的Bucket名称",
Region: "ap-shanghai",
Key: filename,
Body: file
}, function(err, data) {
if (err) {
console.error("上传失败", err);
reject(err);
} else {
console.log("上传成功", data);
resolve(data);
}
});
});
}
</script>