《封装方法》常用的方法: 窗口信息、将字符串复制到剪贴板、form表单下载文件、获取全局唯一标识符、平滑滚动到页面顶部

165 阅读2分钟
复制则可使用、亲测有效
export function filterName(id, list) {
  let item = list.filter(_ => id === _.id);
  return item.length !== 0 ? item[0].name : "";
}
/**
 * 获取窗口信息,窗口高度、根元素字体大小、数据加载长度(用于分页加载设置加载长度)
 * @method getViewInfo
 * @param {Object} refsData 元素或组件的引用信息 eg:this.$refs.wrapbox
 * @param {Number} listHeight 数据列表的高度
 * @returns {Object} {height: 684, fontSize: 16, loadSize: 27}
 */
export function getViewInfo(refsData, listHeight = 160) {
  if (!refsData || !listHeight) {
    console.log("请输入viewData的参数($refs(引用信息),listHeight(数据高度))");
  } else {
    let json = {};
    let clientHeight = refsData.clientHeight;
    let fontSize = parseInt(
      document.getElementsByTagName("html")[0].style.fontSize
    );
    let dataLength = clientHeight / ((listHeight / 16) * fontSize);
    json.height = refsData.clientHeight;
    json.fontSize = fontSize;
    json.loadSize = Math.floor(dataLength * 2);
    return json;
  }
}
/**
 * 设置cookie值
 * @method setCookieDay
 * @param {String} cName  cookie键名
 * @param {*} value cookie值
 * @param {Number} expiredays 过期时间以天为单位
 */
export function setCookieDay(cName, value, expiredays) {
  let exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie =
    cName +
    "=" +
    escape(value) +
    (expiredays == null ? "" : ";expires=" + exdate.toGMTString());
}

/**
 * 设置cookie值
 * @method setCookieSec
 * @param {String} cName cookie键名
 * @param {*} value cookie值
 * @param {Number} expireseconds 过期时间以秒为单位
 */
export function setCookieSec(cName, value, expireseconds) {
  let exdate = new Date();
  exdate.setTime(exdate.getTime() + expireseconds * 1000);
  document.cookie =
    cName +
    "=" +
    escape(value) +
    (expireseconds == null ? "" : ";expires=" + exdate.toGMTString());
}

/**
 * 获取cookie值
 * @method getCookie
 * @param {String} cName cookie的key
 * @returns {String} 返回cookie值
 */
export function getCookie(cName) {
  if (document.cookie.length > 0) {
    let cStart = document.cookie.indexOf(cName + "=");
    if (cStart !== -1) {
      cStart = cStart + cName.length + 1;
      let cEnd = document.cookie.indexOf(";", cStart);
      if (cEnd === -1) {
        cEnd = document.cookie.length;
      }

      return unescape(document.cookie.substring(cStart, cEnd));
    }
  }

  return "";
}
/**
 * 格式化文本保留换行空格,将文本的\n,\s 替换成<br/>,&nbsp;
 * @method  formatText
 * @param   {String} strText 文本字符串
 * @return  {String} 返回格式化后的文本字符串
 */
export function formatText(strText) {
  return strText
    .replace(/\r\n/g, "<br/>")
    .replace(/\n/g, "<br/>")
    .replace(/\s/g, "&nbsp;");
}
/**
 * form表单下载文件
 * @method formSubmit
 * @param {Object} params 参数对象
 * @param {String} url
 */
export function formSubmit(params, url) {
  let form = document.createElement("form");
  form.style.display = "none";
  form.action = url;
  form.method = "post";
  document.body.appendChild(form);

  for (var key in params) {
    let input = document.createElement("input");
    input.type = "hidden";
    input.name = key;
    input.value = params[key];
    form.appendChild(input);
  }

  form.submit();
  form.remove();
}
/**
 * 取随机数
 * @method getRandomInt
 * @param {Number} max 随机数最大值
 * @returns {Number}  0~max的随机数
 */
export function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
/**
 * 获取全局唯一标识符
 * @method getUUID
 * @returns {String}  UUID值
 */
export function getUUID() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (
    S4() +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    S4() +
    S4()
  );
}
/**
 * 检测设备类型
 * @method detectDeviceType
 * @returns {String}
 */
export function detectDeviceType() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? "Mobile"
    : "Desktop";
}
/**
 * 平滑滚动到页面顶部
 */
export function scrollToTop() {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
}
/**
 * 将字符串复制到剪贴板
 * @method copyToClipboard
 * @param {String} str 要复制的文本
 */
export function copyToClipboard(str) {
  try {
    const el = document.createElement("input");
    el.value = str;
    // el.setAttribute('readonly', '');
    el.style.position = "absolute";
    el.style.left = "-9999px";
    document.body.appendChild(el);
    // const selected =
    //   document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
    el.select();
    document.execCommand("copy");
    console.log("拷贝成功");
    document.body.removeChild(el);
    // if (selected) {
    //   document.getSelection().removeAllRanges();
    //   document.getSelection().addRange(selected);
    // }
    return true;
  } catch (error) {
    console.log(error);
    return false;
  }
}
/**
 * 防抖函数
 * @method debounce
 * @param {Function} func 执行函数体
 * @param {Number} delay 间隔时间
 */
export function debounce(func, delay = 200) {
  let timer;
  return function(...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
/**
 * 函数节流
 * @method throttle
 * @param {Function} func 执行函数体
 * @param {Number} delay 间隔时间
 */
export function throttle(func, delay = 200) {
  let lastTime;
  let timer;
  return function(...args) {
    // 记录当前函数触发的时间
    let nowTime = Date.now();
    if (lastTime && nowTime - lastTime < delay) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        // 记录上一次函数触发的时间
        lastTime = nowTime;
        // 修正this指向问题
        func.apply(this, args);
      }, delay);
    } else {
      lastTime = nowTime;
      func.apply(this, args);
    }
  };
}
/**
 * 深拷贝
 * @method deepClone
 * @param {Object} obj 拷贝的对象
 */
export function deepClone(obj) {
  var newObj = obj instanceof Array ? [] : {};
  for (var i in obj) {
    newObj[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
  }
  return newObj;
}