前端工具包之小工具

1,408 阅读2分钟

前言

我们在开发过程中,总会封装一些公共函数来作为我们的工具来简化代码或者复用代码,为此,我打算整理一下我日常工作中常用的一些封装的工具函数,本篇文章不重点介绍某个工具,而是一系列小功能的拆分和封装。

系列文章

1.前端工具包之深浅拷贝

2.前端工具包之日期格式化

3.前端工具包之防抖函数

4.前端工具包之小工具

5.前端工具包之log美化

背景

通常开发中我们会遇到各种类似添加移除事件,添加移除样式,获取dom等一系列的小工具,如果每次编写就无法体现代码的复用。为此,专门整理一篇小工具集合,具体分析就不去赘述了,直接上代码,并在注释中说明用途,基本一看就知道是干啥的。

工具封装

/*各类小工具集合*/
const util = {}

/**
 * 更新窗口标题
 * @param {String} title 标题
 */
util.title = function (title) {
  window.document.title = title
}

/**
 * 模拟a标签打开新地址
 * @param {String} url 地址
 * @param {boolean} target 是否新开窗口
 */
util.open = function (url, target) {
  let a = document.createElement('a')
  a.setAttribute('href', url)
  if (target) {
    a.setAttribute('target', '_blank')
  }
  a.setAttribute('id', 'b-link-temp')
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(document.getElementById('b-link-temp'))
}

/**
 * 在某个区间随机一个整数
 * @param min 最小值
 * @param max 最大值
 * @return {number}
 */
util.getRandomInt = function (min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

/**
 * 洗牌函数(用于打乱数组顺序)
 * @param arr 需要洗牌的数组
 */
util.shuffle = function (arr) {
  let newArr = arr.slice()// 复制一个新数组
  for (let i = 0; i < newArr.length; i++) {
    let j = util.getRandomInt(0, i)// 在0-当前循环的位置随机一个位置做交换
    let t = newArr[i]
    newArr[i] = newArr[j]
    newArr[j] = t
  }
  return newArr
}

/**
 * 判断一个值是否在列表中
 */
util.oneOf (value, validList) {
  return validList.indexOf(value) > -1
}

export default util

/**
 * 滚动动画
 * @param el 需要滚动条滚动的dom元素,可以是window对象
 * @param from 滚动起始位置,默认0
 * @param to 滚动目标位置
 * @param duration 滚动持续时间(默认500毫秒)
 * @param endCallback 滚动结束触发回调
 */
export function scrollTop (el, from = 0, to, duration = 500, endCallback) {
  if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = (
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      function (callback) {
        return window.setTimeout(callback, 1000 / 60)
      }
    )
  }
  const difference = Math.abs(from - to)
  const step = Math.ceil(difference / duration * 50)

  function scroll (start, end, step) {
    if (start === end) {
      endCallback && endCallback()
      return
    }

    let d = (start + step > end) ? end : start + step
    if (start > end) {
      d = (start - step < end) ? end : start - step
    }

    if (el === window) {
      window.scrollTo(d, d)
    } else {
      el.scrollTop = d
    }
    window.requestAnimationFrame(() => scroll(d, end, step))
  }

  scroll(from, to, step)
}

以上几个小函数就是我目前在用的几个小工具,后续会继续扩充。希望喜欢的点个赞,谢谢。


开源库

个人主页 | bin-ui | bin-admin