常用代码
处理错误图片
@error="handleImgError($event)"
handleImgError(e) {
e.target.style.display = 'none';
}
随机数
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'));
console.log(dataType(1));
console.log(dataType(true));
console.log(dataType(null));
console.log(dataType(undefined));
console.log(dataType(()=>{}));
console.log(dataType({}));
console.log(dataType([]));
截取字符串
cutString(str = '', maxlen = 3, cutlen = 3, suffix=''){
if (!str) return '';
return str.length > maxlen ? `${str.slice(0, cutlen)}${suffix}` : str;
}
cutString('哈哈哈哈哈啊啊啊', 5, 4, '...');
html 字符转义
function checkHtml(str) {
str = str.replace(/&/g, '&');
str = str.replace(/>/g, '>');
str = str.replace(/</g, '<');
str = str.replace(/"/g, '"');
str = str.replace(/'/g, ''');
return str;
}
dom.innerHtml = checkHtml(html);
去除空格
String(this.inputData).replace(/\s/g, '');
String(this.inputData).trim();
pageshow和pagehide
window.onpageshow = () => {
}
window.onresize = () => {
}
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复制文案到剪切板
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';
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 > 2000 ? window.scrollY / 200 : 10;
const time = 10;
const timer = setInterval(() => {
if (window.scrollY > 10) {
window.scrollTo(0, window.scrollY - step);
} else {
window.scrollTo(0, 0);
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>
遍历字符串给数字加特殊样式
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;
},
重力感应事件
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;
}
获取对象中的值
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));
console.log(numAddCommas2(123456789, 0));
console.log(numAddCommas2(123456789, 2));
console.log(numAddCommas2(123456789, 4));
console.log(numAddCommas1(123456789.12345678));
console.log(numAddCommas2(123456789.12345678, 0));
console.log(numAddCommas2(123456789.12345678, 2));
console.log(numAddCommas2(123456789.12345678, 4));
分阶段固定点位计算当前进度值
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;
}