前端开发相关实用篇【工具函数(JS)】

80 阅读2分钟

开发中常用的一些js工具函数

设计稿px转页面上的px

/**
 * vw单位转px
 * @param value
 * @returns {number}
 */
export const convertVw = (value) => {
  value = value.replace(/vw/g, "");
  return (+value * window.innerWidth) / 100;
};

/**
 * 设计稿px转页面上的px
 * @param value
 */
export const convertPx = (value) => {
  value = value.replace(/px/g, "");
  return (+value * window.innerWidth) / 750;
};

【待完善】生成缓存promise【采用闭包】

【消化一下,bx】


/**
 * 生成缓存promise
 * @param {function} promiseFn
 * @return {function}
 */
export default function createCachePromise(promiseFn){
  let _promise = null

  /**
   * 是否刷新
   */
  return function(refresh = false){
    if(_promise && !refresh){
      return _promise
    }

    _promise = promiseFn.call(this)

    if(!(_promise instanceof Promise)){
      _promise = Promise.resolve(_promise)
    }

    return _promise
  }
}

【待完善】Promise封装

// 这样封装的优势??


export default function promiseWithResolvers<T>() {
  let resolve: (value: T | PromiseLike<T>) => void;
  let reject: (reason?: any) => void;
  let promise = new Promise<T>((res, rej) => {
    resolve = res;
    reject = rej;
  });
  // @ts-ignore
  return { reject, resolve, promise };
}

// 显示
const show = () => {
  importStateInfo.value = undefined;
  setPageState(PageStates.Default);
  uploadRef.value?.clearFiles();
  files.value = [];

  setVisible(true);

  let { promise, resolve } = promiseWithResolvers<DialogActionType>();
  resolveCache = resolve;
  return promise;
};

实现拖拽效果

获取地理位置

// 获取用户地址位置
export const getUserLocation = () => {
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      // 获取地理位置
      navigator.geolocation.getCurrentPosition(
        function (position) {
          // 获取经纬度信息
          const latitude = position.coords.latitude;
          const longitude = position.coords.longitude;
          if (latitude && longitude) {
            const userGeoLocation = wgs84togcj02(longitude, latitude);
            resolve({
              latitude: userGeoLocation[1].toFixed(6),
              longitude: userGeoLocation[0].toFixed(6),
            });
          } else {
            reject();
          }
        },
        function (error) {
          // 获取地理位置失败
          console.error("获取地理位置失败:" + error.message);
          reject();
        }
      );
    } else {
      // 浏览器不支持Geolocation API
      console.error("浏览器不支持Geolocation API");
      reject();
    }
  });
};

h5监听页面显示/切入前台时触发【或者浏览器从一个tab标签页切回来】

对应taro的useDidShow

 /**
 * 获取浏览器hidden属性名
 * @returns {String} hidden属性
 */
 function getHiddenProp() {
  // hidden属性是原生支持的则直接返回
  if ('hidden' in document) {
      return 'hidden'
  }

  // 其他情况则做前缀处理兼容老版本浏览器
  let hiddenProp = ''
  const prefixes = ['webkit', 'moz', 'ms', 'o']
  prefixes.some(prefix => {
      if (prefix + 'Hidden' in document) {
          hiddenProp = prefix + 'Hidden'
          return true
      }
  })

  return hiddenProp
}

/**
* 监听visibilityChange
* @param {Function} func
*/
export function listenVisibilityChange(func) {
  if(process.env.TARO_ENV === 'h5'){
    const hidden = getHiddenProp() // ios7.1及以上支持 android4.4 开始支持 document.hidden
    if (typeof document.addEventListener === 'undefined' || !hidden) {
        return
    }
    // eslint-disable-next-line
    const visibilityChange = hidden.replace(/[H|h]idden/, '') + 'visibilitychange'
    document.addEventListener(visibilityChange,
      () => {
          func(document[hidden])
      },
      false
    )
  }
}

从Url中获取参数

/**
 * 从url中获取参数
 * @param url
 * @param key
 * @return {{}}
 */
export const getQueryFromURL = (key:string = '', url:string = '') => {
  if (!url) {
    // eslint-disable-next-line no-param-reassign
    url = window.location.href;
  }
  // result为存储参数键值的集合
  const result:any = {};

  // str为?之后的参数部分字符串
  const str = url.substr(url.indexOf('?') + 1);
  // arr每个元素都是完整的参数键值
  const arr = str.split('&');

  for (let i = 0; i < arr.length; i++) {
    // item的两个元素分别为参数名和参数值
    const item = arr[i].split('=');
    result[item[0]] = item[1] ? decodeURIComponent(item[1]) : '';
  }

  if (key) {
    return result[key];
  }
  return result;
};

纯js实现toast

let toastDiv:any = null;

const createToastDiv = () => {
  const toast = document.createElement('div');
  toast.className = 'survey-toast';
  toast.style.cssText = `
    position: fixed;
    max-width: 200px;
    min-height: 28px;
    min-width: 28px;
    white-space: pre-wrap;
    word-break:break-all;
    text-align: left;
    padding: 8px 16px;
    border-radius: 8px;
    font-size: 14px;
    line-height: 20px;
    color: #ffffff;
    background: rgba(0, 0, 0, 0.75);
    z-index: 1000;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    box-sizing: border-box;
  `;
  return toast;
};

const bodyEle = document.body;

let tid:any = null;

export const hideToast = () => {
  if (tid) {
    clearTimeout(tid);
    tid = null;
  }
  toastDiv.style.display = 'none';
};

export const showToast = (msg:string, duration:number = 3000) => {
  if (!toastDiv) {
    toastDiv = createToastDiv();
    bodyEle.appendChild(toastDiv);
  }

  toastDiv.style.display = 'inline-block';
  toastDiv.textContent = msg;

  if (tid !== null) {
    clearTimeout(tid);
  }
  setTimeout(() => {
    hideToast();
  }, duration);
};