前端常用工具类方法总结

104 阅读2分钟

就本人平时所用的前端常用工具类方法记录一下,有需要的可以随时获取,且不定时更新,大家一起学习进步,主要按模块分类:

1.防抖
/**
 * 防抖
 * @param fn 
 * @param delay 
 * @returns 
 */
export function debounce(fn, delay) {
  let timrs;
  return function (...args) {
    clearTimeout(timrs);
    timrs = setTimeout(() => {
      // @ts-ignore
      fn.apply(this, args);
    }, delay);
  }
}
2.图片篇
/**
 * 是否是图片格式的链接
 * @param url 
 */
export function isImage(url) {
  const fileType = url.slice(url.lastIndexOf('.') + 1);
  return ['png', 'jpg', 'jpeg'].includes(fileType.toLowerCase());
}
3.样式篇
/**
 * 行内样式单位转换
 * @param px 
 * @returns 
 */
export function px2rem(px) {
  if (/%/ig.test(px)) {
    return px;
  } else {
    return (parseFloat(px) / 100) + 'rem'
  }
}
4.页面内容
/**
 * 全屏事件
 * @param el
 */
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());
  }
}
/**
 * 获取路由参数
 * @param {*} name 参数名
 */
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.其他
/**
 * 生成随机字符串
 * @param length 
 * @param chars 
 * @returns 
 */
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;
}
/**
 * 平铺数组
 * @param arr
 * @returns
 */
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;
}

/**
 * 数字转中文
 * @param num
 * @returns {*}
 */
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;
}
/**
* 定时器
* @param delay 定时时间 
* @returns 
*/
export const sleep = (delay = 2000) => new Promise((resolve) => setTimeout(resolve, delay));
/**
 * 轮巡执行函数
 * @param fn 执行函数
 * @param time 周期时间
 * @param opt 配置 once:只执行一次
 */
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;
}
/**
 * 计算会议时间
 * @param startTime 开始时间
 * @param endTime 结束时间
 */
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
  }`;
  //console.log(str);
  return str;
}

/**
 * 计算会议持续时间
 * @param startTime 开始时间
 * @param endTime 结束时间
 * @returns
 */
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,
  };
}

/**
 * h5获取视频上传时第一帧作为视频封面
 * @param 
 * @param 
 * @returns
 */
<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() {
        // 创建 Canvas
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;

        // 绘制视频第一帧到 Canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

        // 获取封面图 Blob
        canvas.toBlob(async function(blob) {
            // 预览封面图
            const thumbnailImg = document.getElementById('thumbnail');
            thumbnailImg.src = URL.createObjectURL(blob);
            thumbnailImg.style.display = 'block';

            // 🔥 上传封面图到 COS
            await uploadToCOS(blob, 'video-thumbnail.jpg');

            // 🔥 上传视频文件到 COS
            await uploadToCOS(file, 'uploaded-video.mp4');
        }, 'image/jpeg');
    });
});

// 🔥 上传到腾讯云 COS(需要填写你的密钥和 Bucket 信息)
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>