JavaScript工具函数(浏览器环境,持续更新)

JavaScript8 个月前1546

前端业务中比较常用的JavaScript工具函数,浏览器环境常用,可直接拷贝在项目里使用。这里统一整理,方便查阅,本文章会持续更新。

一、file转为base64

/**
 * file转为base64
 * @param {*} file file对象
 * @param {*} callback 
 */
export const fileToDataURL = (file, callback) => {
    let freader = new FileReader();
    freader.readAsDataURL(file);
    freader.onload = function (e) { callback(e.target.result); }
}

二、blob流转换为base64

/**
 * blob流转换为base64
 * @param {*} blob blob对象
 * @param {*} callback 
 */
export const blobToDataURL = (blob, callback) => {
    let freader = new FileReader();
    freader.readAsDataURL(blob);
    freader.onload = function (e) { callback(e.target.result); }
}

三、base64转换为blob

/**
 * base64转换为blob
 * @param {*} dataurl base64
 */
export const dataURLtoBlob = (dataurl) => {
    let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

四、base64转换为file,IE低版本不兼容

/**
 * 将base64转换为file,IE低版本不兼容
 * @param {*} dataurl base64
 * @param {*} filename 文件名
 */
export const dataURLtoFile = (dataurl, filename) => {
    let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

五、图片url转化成base64

/**
 * 图片url转化成base64
 * @param {*} url 图片url
 * @param {*} callback 
 * @param {*} outputFormat 图片格式
 */
export const imgUrlToDataURL = (url, callback, outputFormat) => {
    let canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        img = new Image;
    img.crossOrigin = 'Anonymous';
    img.src = url + "?timeStamp=" + new Date().getTime();
    img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        // ctx.drawImage(img, 0, 0);
        ctx.drawImage(this, 0, 0, img.width, img.height);
        let dataURL = canvas.toDataURL(outputFormat || 'image/png');
        // callback.call(this, dataURL);
        callback && callback(dataURL)
        canvas = null;
    };
}

六、获取窗口尺寸

export function getViewportSize() {
  let w = 0;
  let h = 0;
  if (window.innerWidth) {
    w = window.innerWidth
    h = window.innerHeight
  } else if (document.body && document.body.clientWidth) {
    w = document.body.clientWidth
    h = document.body.clientHeight
  } else if (document.documentElement && document.documentElement.clientWidth) {
    w = document.documentElement.clientWidth
    h = document.documentElement.clientHeight
  }
  return { w, h }
}

七、浏览器环境检测

const ua = window.navigator.userAgent.toLowerCase()

// 是否微信
export const isWx = () => ua.match(/MicroMessenger/i) == 'micromessenger'

// 是否ipad
export const isIpad = () => ua.indexOf('ipad') > -1

// 是否iphone
export const isIphone = () => ua.indexOf('iphone os') > -1

// 是否uc
export const isUc = () => ua.indexOf('ucweb') > -1

// 是否windows pc
export const isWindows = () => ua.indexOf('windows') > -1

// 是否android
export const isAndroid = () => ua.indexOf('android') > -1 || ua.indexOf('adr') > -1

// 是否ios
export const isIos = () => /(iphone|ipod|ipad|ios)/i.test(ua)

// 是否qq浏览器
export const isQq = () => ua.indexOf('mqqbrowser') > -1 && ua.indexOf(' qq') < 0

// 是否qq内置浏览器
export const isQQInstalled = () => ua.indexOf(' qq') > -1 && ua.indexOf('mqqbrowser') < 0

八、开启与关闭全屏

// 开启全屏
export function launchFullscreen(element) {
  element = element || document.documentElement
  if (element.requestFullscreen) {
    element.requestFullscreen()
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen()
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen()
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen()
  }
}

// 关闭全屏
export function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen()
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen()
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen()
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen()
  }
}

九、返回顶部/指定位置,实现滚动动画

/**
 * @param {*} number 距离页面顶部的距离
 * @param {*} time 滚动所需时间 单位ms
 */
const scrolling = (number = 0, time) => {
    if (!time) {
        document.body.scrollTop = document.documentElement.scrollTop = number;
        return number;
    }
    // 设置循环的间隔时间  值越小消耗性能越高
    const spacingTime = 20;
    // 计算循环的次数
    let spacingInex = time / spacingTime; 
    // 获取当前滚动条位置
    let nowTop = document.body.scrollTop + document.documentElement.scrollTop; 
    // 计算每次滑动的距离
    let everTop = (number - nowTop) / spacingInex;

    let scrollTimer = setInterval(() => {
        if (spacingInex > 0) {
            spacingInex--;
            ScrollTop(nowTop += everTop);
        } else {
            clearInterval(scrollTimer); // 清除计时器
        }
    }, spacingTime);
};

// 滚动到距离页面顶部500px的位置 动画时间为300ms
// scrolling(500, 300);

十、实现锚点滚动

// 运用了H5的scrollIntoView方法,这是一个实验中的功能,IE 8以下、Safari 6以下、Safari on iOS 5以下不兼容
const scrollToAnchor = (anchorName) => {
    if (anchorName) {
        // 找到锚点
        let anchorElement = document.getElementById(anchorName);
        // 如果对应id的锚点存在,就跳转到锚点
        if (anchorElement) {
            anchorElement.scrollIntoView({
                behavior: 'auto', // 定义动画过渡效果, "auto""smooth" 之一。默认为 "auto"
                block: 'start', // 定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"
                inline: 'nearest', // 定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"
            });
        }
    }
}
1 条评论

    👸 👸 👸 👸 👸 

    3