lodash和utils常用工具库

判断移动端和ipados

export const isTouchDevice = (): boolean => {
  if (typeof window !== 'undefined') {
    return /(iPhone|iPod|iPad|Android|playbook|silk|BlackBerry|BB10|Windows 
    Phone|Tizen|Bada|webOS|IEMobile|Opera Mini)/gi.test(
   
      navigator.userAgent,
    );
  }

};


function iPadOS() {
  let ua = '';
  if (typeof window !== 'undefined') {
    ua = navigator.userAgent;
  }

  ua = ua || '从别的渠道获取ua信息' || '';
  const isSafari = ua.includes('Safari') && ua.includes('Version');
  const isIphone = ua.includes('iPhone') && ua.includes('Version');
  const isIPad =
    isSafari &&
    !isIphone &&
    (isTouchDevice() ||
      'ontouchstart' in window ||
      navigator.maxTouchPoints > 0);
  return isIPad;
}

判断移动和PC设备

function isMobile(){
  if(typeof window !== 'undefined'){
    return /(iphone|ipad|android|mobile)/gi.test
    (navigator.userAgent)
  }
}

function checkOnmobileDevice(){
	 return(
	 isMobile()||
    typeof window !== 'undefined'&&
    window.innerWidth<720&&
    window.innerHeight > window.innerWidth
  )
}

useRem

function onResize(){
  let fontSize = 16;
  //414设计稿的宽度 一般移动端都是375
  fontSize = (innerWidth/414)*100
  documnet.documentElement.style.fontSize = `${fontSize}px`;
}

window.addEventListener('resize',onResize)

beforeunload

当浏览器窗口关闭或者刷新时,会触发beforeunload事件
。当前页面不会直接关闭,可以点击确定按钮关闭或刷新,
也可以取消关闭或刷新。

window.addEventListener('beforeunload',
()=>{setUnload(true)})

获取环境

process.env

获取浏览器类型和函数

// 各主流浏览器
function getBrowser() {
    var u = navigator.userAgent;
 
    var bws = [{
        name: 'sgssapp',
        it: /sogousearch/i.test(u)
    }, {
        name: 'wechat',
        it: /MicroMessenger/i.test(u)
    }, {
        name: 'weibo',
        it: !!u.match(/Weibo/i)
    }, {
        name: 'uc',
        it: !!u.match(/UCBrowser/i) || u.indexOf(' UBrowser') > -1
    }, {
        name: 'sogou',
        it: u.indexOf('MetaSr') > -1 || u.indexOf('Sogou') > -1
    }, {
        name: 'xiaomi',
        it: u.indexOf('MiuiBrowser') > -1
    }, {
        name: 'baidu',
        it: u.indexOf('Baidu') > -1 || u.indexOf('BIDUBrowser') > -1
    }, {
        name: '360',
        it: u.indexOf('360EE') > -1 || u.indexOf('360SE') > -1
    }, {
        name: '2345',
        it: u.indexOf('2345Explorer') > -1
    }, {
        name: 'edge',
        it: u.indexOf('Edge') > -1
    }, {
        name: 'ie11',
        it: u.indexOf('Trident') > -1 && u.indexOf('rv:11.0') > -1
    }, {
        name: 'ie',
        it: u.indexOf('compatible') > -1 && u.indexOf('MSIE') > -1
    }, {
        name: 'firefox',
        it: u.indexOf('Firefox') > -1
    }, {
        name: 'safari',
        it: u.indexOf('Safari') > -1 && u.indexOf('Chrome') === -1
    }, {
        name: 'qqbrowser',
        it: u.indexOf('MQQBrowser') > -1 && u.indexOf(' QQ') === -1
    }, {
        name: 'qq',
        it: u.indexOf('QQ') > -1
    }, {
        name: 'chrome',
        it: u.indexOf('Chrome') > -1 || u.indexOf('CriOS') > -1
    }, {
        name: 'opera',
        it: u.indexOf('Opera') > -1 || u.indexOf('OPR') > -1
    }];
 
    for (var i = 0; i < bws.length; i++) {
        if (bws[i].it) {
            return bws[i].name;
        }
    }
 
    return 'other';
}
 
// 系统区分
function getOS() {
    var u = navigator.userAgent;
    if (!!u.match(/compatible/i) || u.match(/Windows/i)) {
        return 'windows';
    } else if (!!u.match(/Macintosh/i) || u.match(/MacIntel/i)) {
        return 'macOS';
    } else if (!!u.match(/iphone/i) || u.match(/Ipad/i)) {
        return 'ios';
    } else if (!!u.match(/android/i)) {
        return 'android';
    } else {
        return 'other';
    }
}

image+canvas图片上传

 export const converImgToBase64: (url: string) => Promise<string>
    = (url: string){
      new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        if (ctx) {
          const img = new Image();
          img.crossOrigin = 'Anonymous'
          img.onload = function () {
            canvas.height = img.height
            canvas.width = img.width
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
            const dataUrl = canvas.toDataURL();
            resolve(dataUrl)
          }
          img.onerror = function (err) {
            reject(err)
          }
          img.src = url;
        }
      })
    }
  const sliceBase64Header = (base64String: string) =>
    base64String.replace(/^data:image\/[a-z]{3,4};base64,/, '')

  const converUploadImageToPureBaase64 =
    (upload: string | File): Promise<string> => {
      new Promise(resolve => {
        let image_base64 = '';
        if (typeof upload === 'string') {
          converImgToBase64(upload).then(dataUrl => {
            image_base64 = sliceBase64Header(dataUrl);
            resolve(image_base64)
          })
        } else {
          const reader = new FileReader();
          reader.readAsDataURL(upload);
          reader.onload = function (e) {
            image_base64 = sliceBase64Header(
              await converImgToBase64(e.target.result as string)
            );
            resolve(image_base64)
          }
        }
      })
    }

处理input文件上传

MDN WEB API file文件处理 链接

移动端适配rem

(function () {
  function resize() {
    //设计稿的宽度
    const desiginWidth = 375;
    //视口的宽度
    const windowWidth = window.innerWidth;
    //html节点
    const html = document.documentElement;
    //计算  -- 字体大小
    html.style.fontSize = 100 / desiginWidth * windowWidth + 'px';
  }
  resize();
  //判断是否有横屏事件,有横屏优先执行横屏,没有横屏,执行resize事件
  window.addEventListener('onorientationchange' in window ? 'onorientationchange' : 'resize', resize);
  //监听文档加载完成
  window.addEventListener('DOMContentLoaded', resize)
}(document, window));

anchor组件左右对应关系

export function onScroll(metaRef) {
  if (!partnerTitle) {
    partnerTitle = document.getElementById('partner_title_VC');
  }
  const { innerHeight } = window;
  const anchor = metaRef.current.anchorRef?.dom;
  const { top } = partnerTitle.getBoundingClientRect();
  if (anchor) {
    if (top < innerHeight) {
      anchor.style.transform = `translate3d(0, -${innerHeight - top}px, 0)`;
    } else {
      anchor.style.transform = `translate3d(0, 0, 0)`;
    }
  }

屏幕宽度尺寸

  useEffect(() => {
    if (window?.matchMedia('screen and (max-width:1024px)')?.matches) {
      setIsFold(true);
    }
  }, []);

版权声明:本文为qq_36262295原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。