前端项目开发中常用的工具函数集合分享

1,132 阅读3分钟

第一个: 改浏览器滚动条的样式(仿mac)

 
 /* 设置滚动条的样式 */
 ::-webkit-scrollbar {
     background-color: transparent;
     width: 12px;
 }
 
 ::-webkit-scrollbar-thumb {
     background-color: transparent;
     border-radius: 8px;
     background-clip: content-box;
     border: 2px solid transparent;
 }
 
 body[scroll]::-webkit-scrollbar-thumb,
 ::-webkit-scrollbar-thumb:hover {
     background-color: rgba(0, 0, 0, .5);
 }

JS:(优化体验) 当停止滚动之后,自动隐藏滚动条 当开始滚动时,自动显示滚动条

 // 设置滚动条的隐藏 
 // 设计思路 监听滚动事件,滚懂就显示滚动条,不滚动添加定时器,500ms后隐藏
 window.addEventListener('scroll', function (ev) {
     document.body.toggleAttribute('scroll', true)
     this.timer && clearTimeout(this.timer)
     this.timer = setTimeout(() => {
         document.body.toggleAttribute('scroll')
     }, 500)
 })

第二个:毛玻璃的实现效果(CSS)

 .NowInfo {
   width: 800px;
   height: 220px;
   padding: 20px 20px 10px 20px;
   background: rgba(255, 255, 255, 0.1);
   border-radius: 10px;
   backdrop-filter: blur(10px);
   box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
 }

第三个 : 返回顶部 按钮

         const backTop = document.querySelector('.backTop')
         backTop.addEventListener('click', () => {
             console.log("212421");
             window.scrollTo({
                 top: 0,
                 behavior: "smooth"
             })
         })

第四个: 返回顶部按钮的隐藏 和 显示

节流 减少频繁滚动事件

 let throttle = function (fn, delay) {
             let timer = null;
             return function () {
                 let context = this;
                 let args = arguments;
                 if (!timer) {
                     timer = setTimeout(function () {
                         fn.apply(context, args);
                         timer = null;
                     }, delay);
                 }
             };
         };
         window.addEventListener('scroll', throttle(() => {
             console.log(123);
             let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
             if (scrollTop >= 500) {
                 backTop.style.display = "none"
             } else {
                 backTop.style.display = "block"
 ​
             }
         }, 500))

第五个: JS高级注释

当我们编写JavaScript代码时,可以使用高级注释来记录一些信息,比如作者、修改日期、项目进度、待办事项等等。这些信息可以帮助其他开发人员更好地了解代码的背景和用途。

下面是一个例子,记录了一个JavaScript函数的作者、创建日期和待办事项:

 /**
  * @description 这是一个简单的加法函数
  * @param {number} a - 加数
  * @param {number} b - 加数
  * @returns {number} - 两个数字的和
  * @author John Doe
  * @created 2023-04-06
  * @todo 这个函数需要添加错误处理机制
  */
 function add(a, b) {
   return a + b;
 }

使用了以 @ 开头的注释标签来记录不同的信息。其中,@description 描述了函数的作用,@param@returns 分别描述了函数的参数和返回值。而 @author@created@todo 则是我们自定义的注释标签,分别记录了函数的作者、创建日期和待办事项。

这样,其他开发人员在阅读代码时,就可以通过查看高级注释了解更多的信息,从而更好地维护和扩展代码。

第六个: 节流函数(Throttle)

节流函数用于限制函数执行的频率,常用于滚动、窗口缩放等频繁触发的事件。

function throttle(fn, delay) {
  let timer = null;
  return function () {
    const context = this;
    const args = arguments;
    if (timer === null) {
      timer = setTimeout(() => {
        fn.apply(context, args);
        timer = null;
      }, delay);
    }
  };
}

第七个: 防抖函数(Debounce):

防抖函数确保函数在事件触发后等待一定的延迟时间才执行,适用于输入框搜索等场景。

function debounce(fn, delay) {
  let timer = null;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, delay);
  };
}

第八个: 获取浏览器视口大小:

获取浏览器当前的视口(viewport)宽度和高度。

function getViewportSize() {
  return {
    width: window.innerWidth,
    height: window.innerHeight
  };
}

第九个: 检查是否为移动端设备:

判断当前访问设备是否为移动端设备。

function isMobileDevice() {
  return /Mobi|Android/i.test(navigator.userAgent);
}

第十个: 复制到剪贴板:

将文本复制到剪贴板。

function copyToClipboard(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}

第十一个: 生成随机ID

生成一个随机的ID,常用于列表项或组件的key。

function generateRandomId() {
  return Math.random().toString(36).substr(2, 9);
}

第十二个: 生成随机16进制颜色值

返回生成一个随机的十六进制颜色

function getRandomHexColor() {
    return `#${Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')}`;
}
console.log(getRandomHexColor());

第十三个: 获取DOM的宽高

function getElementSize(element) {
  const rect = element.getBoundingClientRect();
  return {
    width: rect.width,
    height: rect.height
  };
}

第十四个: 数组分页

将数组分割成多个子数组,每个子数组包含指定数量的元素

function paginateArray(array, pageSize) {
  const pages = [];
  for (let i = 0; i < array.length; i += pageSize) {
    pages.push(array.slice(i, i + pageSize));
  }
  return pages;
}

第十五个: 数组去重

对数组进行去重,用到Set结构的特性

function uniqueArray(array) {
  return [...new Set(array)];
}