前端工具包之小工具

前言

咱們在開發過程當中,總會封裝一些公共函數來做爲咱們的工具來簡化代碼或者複用代碼,爲此,我打算整理一下我平常工做中經常使用的一些封裝的工具函數,本篇文章不重點介紹某個工具,而是一系列小功能的拆分和封裝。前端

系列文章

1.前端工具包之深淺拷貝git

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

3.前端工具包之防抖函數數組

4.前端工具包之小工具bash

5.前端工具包之log美化app

背景

一般開發中咱們會遇到各類相似添加移除事件,添加移除樣式,獲取dom等一系列的小工具,若是每次編寫就沒法體現代碼的複用。爲此,專門整理一篇小工具集合,具體分析就不去贅述了,直接上代碼,並在註釋中說明用途,基本一看就知道是幹啥的。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)
}
複製代碼

以上幾個小函數就是我目前在用的幾個小工具,後續會繼續擴充。但願喜歡的點個贊,謝謝。ide


開源庫

我的主頁 | bin-ui | bin-admin函數

相關文章
相關標籤/搜索