常用代码

处理错误图片

@error="handleImgError($event)"

handleImgError(e) {
  e.target.style.display = 'none';
  // e.target.setAttribute('src', defaultImg);
}

随机数

// 生成随机数
function randomNum(min, max) {
  return parseInt(Math.random() * (max - min + 1) + min, 10);
}

// 平衡随机数
let lastRandomPos = 'right';
function balanceRandomNum(min, max) {
  const tempRandom = parseInt(Math.random() * (max - min + 1) + min, 10);
  console.log(Math.floor((max-min+1)/2));
  const tempRandomPos = tempRandom <= Math.ceil((max-min + 1)/2) ? 'left' : 'right';
  const isEqual = lastRandomPos === tempRandomPos;
  lastRandomPos = isEqual ? lastRandomPos : tempRandomPos;
  return isEqual ? balanceRandomNum(min, max) : tempRandom;
}

// 平衡随机数-调用
for (let i = 0; i < 100; i++) {
  const random = balanceRandomNum(0, 10);
  console.log(lastRandomPos, random);
}

随机颜色

function randomColor() {
  const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
  let color = '';
  for(let i = 0; i < 6; i++) {
    color += arr[this.randomNum(0, 15)];
  }
  return `#${color}`;
}

判断数据类型

function dataType(data) {
  const type = Object.prototype.toString.call(data);
  return type.replace(/(\[object |\])/gi, '').toLowerCase();
}

console.log(dataType('a')); // string
console.log(dataType(1)); // number
console.log(dataType(true)); // boolean
console.log(dataType(null)); // null
console.log(dataType(undefined)); // undefined
console.log(dataType(()=>{})); // function
console.log(dataType({})); // object
console.log(dataType([])); // array

截取字符串

/**
 * @param {string} str 截取的字符串
 * @param {number} maxlen 超出上限
 * @param {number} cutlen 截取长度
 * @param {string} suffix 超出替换字符,如:...
 * @returns {string}
 */
cutString(str = '', maxlen = 3, cutlen = 3, suffix=''){
  if (!str) return '';
  return str.length > maxlen ? `${str.slice(0, cutlen)}${suffix}` : str;
}

cutString('哈哈哈哈哈啊啊啊', 5, 4, '...'); // 哈哈哈哈哈...

html 字符转义

// 可防止 XSS 攻击
function checkHtml(str) {
  str = str.replace(/&/g, '&amp;');
  str = str.replace(/>/g, '&gt;');
  str = str.replace(/</g, '&lt;');
  str = str.replace(/"/g, '&quot;');
  str = str.replace(/'/g, '&#39;');
  return str;
}

dom.innerHtml = checkHtml(html);

去除空格

// 去除所有空格
String(this.inputData).replace(/\s/g, '');
// 去除前后空格
String(this.inputData).trim();

pageshow和pagehide

window.onpageshow = () => {
  // TODO
}

window.onresize = () => {
  // TODO
}

dom派发事件dispatchEvent

function touchEvent(id = '', event = 'click') {
  if (!id) return;
  const dom = document.querySelector(`#${id}`);
  if (!dom) return;

  const e = document.createEvent('MouseEvent');
  e.initEvent(event, false, false);
  dom.dispatchEvent(e);
}

H5复制文案到剪切板

// 兼容iOS & Android,创建textarea或input元素
copyData(code) {
  const textArea = document.createElement('textarea');
  textArea.style.position = 'absolute';
  textArea.style.top = 0;
  textArea.style.left = '-1000px';
  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';
  textArea.style.color = 'rgba(0, 0, 0, 0)';
  textArea.style.background = 'transparent';
  textArea.id = 'copyDom';
  textArea.value = code;
  textArea.readOnly = 'readOnly'; // iOS端会弹起键盘,需设置为只读属性
  document.body.appendChild(textArea);
  // 执行复制操作
  textArea.select();
  textArea.setSelectionRange(0, textArea.value.length);
  document.execCommand('Copy');
  // 复制结果反馈
  try {
    const msg = document.execCommand('copy') ? '成功' : '失败';
    toast(`复制${msg}`);
  } catch (err) {
    toast('不支持复制哦~');
  }
  document.body.removeChild(textArea);
}

h5监听物理返回键

// 添加历史记录
if(window.history && window.history.pushState) {
  window.history.pushState('second', null, './#second');
}

// 删除历史记录
if(window.history && window.history.pushState) {   
  window.history.go(-1);   
}

// 物理键监听           
if(window.history && window.history.pushState) {                                  
  $(window).on('popstate', function() { 
    window.history.go(-1);                                        
  });                            
}

返回顶部backToTop

backToTop() {
  // const step = window.scrollY / 100; // 1000ms回到顶部 / 100, 2000ms回到顶部 / 200
  // const step = 10; // 固定步数,页面越长,回到页面时间越长。
  const step = window.scrollY > 2000 ? window.scrollY / 200 : 10;
  const time = 10;
  const timer = setInterval(() => {
    if (window.scrollY > 10) {
      window.scrollTo(0, window.scrollY - step); // x,y
    } else {
      window.scrollTo(0, 0); // x,y
      clearInterval(timer);
    }
  }, time);
}

json实时显示

<template>
  <div>
    <h3>{{ title }}</h3>
    <pre><code>{{ valueString }}</code></pre>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "json显示",
      value: [
        { name: "aaa", age: 11 },
        { name: "bbb", age: 22 },
        { name: "ccc", age: 33 }
      ]
    };
  },
  computed: {
    valueString() {
      return JSON.stringify(this.value, null, 2);
    }
  }
};
</script>

<style scoped>
pre {
  text-align: start;
}
</style>

遍历字符串给数字加特殊样式

// 1、给字符串中的数字加 span 标签;  2、给标签设置特殊样式。
handleNumberStyle(str) {
 let newStr = '';
 for (let i = 0; i < str.length; i++) {
  const reg = /^[0-9]$/g;
  if (reg.test(Number(str[i]))) {
   newStr += `<span>${str[i]}</span>`;
  } else {
   newStr += str[i];
  }
 }
 return newStr;
},

重力感应事件

// 运用HTML5的deviceMotion,调用重力感应事件
var speed = 30;
var x = y = z = lastX = lastY = lastZ = 0;
if(window.DeviceMotionEvent){
  document.addEventListener('devicemotion', deviceMotionHandler, false)
}
function deviceMotionHandler(eventData) {
  var acceleration = event.accelerationIncludingGravity;
  x = acceleration.x;
  y = acceleration.y; 
  z = acceleration.z;
  if(Math.abs(x - lastX) > speed || Math.abs(y - lastY) > speed || Math.abs(z - lastZ) > speed ){
    //这里是摇动后要做的事情
  }
  lastX = x;
  lastY = y;
  lastZ = z;
}

获取对象中的值

/**
 * @description: 获取对象中的值
 * @param {Array} path a.b.c=[a, b, c] a.b[0].c[1]=[a, b, 0, c, 1]
 * @return {Object} obj
 */
function getJsonValue(path = [], obj = {}) {
  return path.reduce((obj, item) => {
    try {
      return obj[item];
    } catch (error) {
      return obj === undefined ? undefined : null;
    }
  }, obj);
}

console.log加样式

console.log(`%c 文本文本文本`, 'background: red; color:#fff;');

数字转3位1逗号

// 数字添加逗号间隔
function numAddCommas1(num) {
  return num.toLocaleString('zh-CN', { style: 'decimal' });
}

// 数字添加逗号间隔
function numAddCommas2(num, fixed) {
  if (!fixed || fixed === 0) {
    return num
      .toFixed(0)
      .toString()
      .replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
  }
  return num
    .toFixed(fixed)
    .toString()
    .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
}

// 测试传入整数
console.log(numAddCommas1(123456789));             // 123,456,789
console.log(numAddCommas2(123456789, 0));          // 123,456,789
console.log(numAddCommas2(123456789, 2));          // 123,456,789.00
console.log(numAddCommas2(123456789, 4));          // 123,456,789.0000
// 测试传入小数
console.log(numAddCommas1(123456789.12345678));    // 123,456,789.123
console.log(numAddCommas2(123456789.12345678, 0)); // 123,456,789
console.log(numAddCommas2(123456789.12345678, 2)); // 123,456,789.12
console.log(numAddCommas2(123456789.12345678, 4)); // 123,456,789.1235

分阶段固定点位计算当前进度值

function progressPercent(currentCount) {
  const computedPercent = (count = 0, numArea = [], percentArea = []) => {
    const [leftNum, rightNum] = numArea;
    const [leftPercent, rightPercent] = percentArea;
    const per1 = ((count - leftNum) / (rightNum - leftNum)).toFixed(1);
    const per2 = ((rightPercent - leftPercent) / 100).toFixed(1);
    const per3 = per1 * (per2 * 100);
    return (leftPercent + per3).toFixed(1);
  }
  // 进度点
  const countArr = [0, 6000, 16000, 28000, 40000];
  const percentArr = [0, 23, 63, 86, 100];
  // 计算进度
  let percent = 0;
  countArr.forEach((item, index) => {
    // 等于节点
    if (currentCount === item) {
      percent = percentArr[index];
    }
    // 节点区间
    if (currentCount > countArr[index] && currentCount < countArr[index + 1]) {
      percent = computedPercent(
        currentCount,
        [countArr[index], countArr[index + 1]],
        [percentArr[index], percentArr[index + 1]]
      )
    }
    // 超出总值
    if (currentCount > item && index === countArr.length - 1) {
      percent = 100;
    }
  });
  if (percent < 1) percent = 1;
  return percent;
}