开发常用:开发项目中,前端常用工具类 整理更新中…

目录

1、函数防抖

2、函数节流

3、移动端的浏览器 window.orientation 参数,通过这个参数可以判断出手机是处在横屏还是竖屏状态

4、判断是否为iphone x

5、获取url参数

6、url参数对象化

7、 url参数对象转字符串

8、判断访问终端

9、图片预加载

10、休眠

11、随机数 min ≤ r < max

12、删除所有的cookies


1、函数防抖

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
export const debounce = (func, wait, immediate) => {
  var timeout

  return function () {
    var context = this
    var args = arguments

    if (timeout) clearTimeout(timeout)
    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(function () {
        timeout = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait)
    }
  }
}

2、函数节流

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版,2 表定时器版
 */
export const throttle = (func, wait, type) => {
  if (type === 1) {
    var previous = 0
  } else if (type === 2) {
    var timeout
  }

  return function () {
    var context = this
    var args = arguments
    if (type === 1) {
      var now = Date.now()

      if (now - previous > wait) {
        func.apply(context, args)
        previous = now
      }
    } else if (type === 2) {
      if (!timeout) {
        timeout = setTimeout(function () {
          timeout = null
          func.apply(context, args)
        }, wait)
      }
    }
  }
}

3、移动端的浏览器 window.orientation 参数,通过这个参数可以判断出手机是处在横屏还是竖屏状态

export const screenDirectionChangeTips = (colFunc, rowFunc) => {
  window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', function () {
    if (window.orientation === 180 || window.orientation === 0) {
      console.log('竖屏状态!')
      if (colFunc && typeof colFunc === 'function') {
        colFunc()
      }
    }
    if (window.orientation === 90 || window.orientation === -90) {
      console.log('横屏状态!')
      if (rowFunc && typeof rowFunc === 'function') {
        rowFunc()
      }
    }
  }, false)
}

使用案例:

 index.html

    <div id="screen-direction-tips" style="display: none;">
      <div class="content">
        <img src="<%= BASE_URL %>wx-common-images/screen-direction-lock.png" alt="">
        <p>请调整到适合屏幕阅读的方向</p>
      </div>
    </div>

js 控制

import { screenDirectionChangeTips } from '@/utils/utils'
  // 竖屏横屏提醒
  screenDirectionChangeTips(() => {
    // 竖屏状态
    document.querySelector('#screen-direction-tips').style.display = 'none'
  }, () => {
    // 横屏状态
    document.querySelector('#screen-direction-tips').style.display = 'block'
  })

4、判断是否为iphone x

export const isIphoneX = () => {
  return /iphone/gi.test(navigator.userAgent) && (screen.height === 812 && screen.width === 375)
}

5、获取url参数

export const getUrlParam = (name) => {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = decodeURIComponent(window.location.search).substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

举例子:

// 获取url中参数code的值
const code = getUrlParam('code') || ''

6、url参数对象化

// url参数对象化
export const parseUrlParamToObj = (url) => {
  /* eslint-disable-next-line */
  let regUrl = /^[^\?]+\?([\w\W]+)$/
  let regParam = /([^&=]+)=([\w\W]*?)(&|$|#)/g
  let urlStr = decodeURIComponent(url || window.location.href)
  let arrUrl = regUrl.exec(urlStr)
  let ret = {}
  if (arrUrl && arrUrl[1]) {
    var strParam = arrUrl[1]; var result
    while ((result = regParam.exec(strParam)) != null) {
      ret[result[1]] = result[2]
    }
  }
  return ret
}

7、 url参数对象转字符串

// url参数对象转字符串
export const parseUrlParamToStr = (obj) => {
  let urlSearchStr = '?'
  let urlOrigin = window.location.origin
  let urlPathname = window.location.pathname
  if (Object.keys(obj).length === 0) {
    return urlOrigin + urlPathname
  } else {
    for (let key in obj) {
      urlSearchStr += `${key}=${obj[key]}&`
    }
    urlSearchStr = urlSearchStr.slice(0, urlSearchStr.lastIndexOf('&'))
    return urlOrigin + urlPathname + urlSearchStr
  }
}

8、判断访问终端

export const browser = {
  versions: (function () {
    let u = navigator.userAgent
    // let app = navigator.appVersion
    return {
      trident: u.indexOf('Trident') > -1, // IE内核
      presto: u.indexOf('Presto') > -1, // opera内核
      webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, // android终端
      iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1, // 是否iPad
      webApp: u.indexOf('Safari') === -1, // 是否web应该程序,没有头部与底部
      weixin: u.indexOf('MicroMessenger') > -1, // 是否微信
      qq: u.match(/\sQQ/i) === 'qq' // 是否QQ
    }
  }()),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

例子:判断是否为微信环境

import {
  browser,
} from '@/utils/utils'

let isWeixin = browser.versions.weixin

9、图片预加载

export const preloadImage = (names, cb, prefix, cacheName = 'cachImage') => {
  window[cacheName] = window[cacheName] || []
  let n = 0
  let img = null
  let imgs = {}
  let date = new Date()
  console.group('---- %s ----', date)
  names.forEach(function (name) {
    img = new Image()
    window[cacheName].push(img)
    img.onload = (function (name, img) {
      return function () {
        imgs[name] = img
        ++n === names.length && cb && cb(imgs)
      }
    })(name, img)
    console.log((prefix || '') + name)
    img.src = (prefix || '') + name
  })
  console.groupEnd()
}

 图片预加载 preLoadImage.js

import { preloadImage } from '@/utils/utils'
import config from '@/config/'

const preLoadImageDemo = () => {
  return new Promise((resolve, reject) => {
    preloadImage(
      [

      ], // 图片名称数组
      function () {
        resolve('imageDemo')
        console.log('imageDemo preLoad success...')
      },
      config.publicPath, // 路径
      'imageDemo' // 缓存名称
    )
  }).catch()
}

const preloadImageAllPromise = () => {
  return new Promise((resolve, reject) => {
    document.querySelector('#loading').style.display = 'block'
    Promise.all([
      preLoadImageDemo()
    ])
      .then(res => {
        console.log(res)
        console.log('all preload success...')
        resolve('success')
        document.querySelector('#loading').style.display = 'none'
      })
      .catch()
  })
}

export { preloadImageAllPromise }

例子:

import { preloadImageAllPromise } from '@/utils/preLoadImage'
        preloadImageAllPromise().then(res => {
          if (res === 'success') {
            new Vue({
              render: h => h(renderApp)
            }).$mount('#app')
          }
        })

10、休眠

export const sleep = (ms) => {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

11、随机数 min ≤ r < max

export const randomNum = (Min, Max) => {
  let Range = Max - Min
  let Rand = Math.random()
  let num = Min + Math.floor(Rand * Range) // 舍去
  return num
}

12、删除所有的cookies

export const deleteAllCookies = () => {
  let cookies = document.cookie.split(`;`)

  for (let i = 0; i < cookies.length; i++) {
    let cookie = cookies[i]
    let eqPos = cookie.indexOf(`=`)
    let name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie
    document.cookie = name + `=;expires=Thu, 01 Jan 1970 00:00:00 GMT`
  }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值