前端常用JS代码片段 - DOM相关操作
日常积累了一些常用JS片段,在此做个总结记录。
# 复制文本
更多高级功能可使用clipboardjs (opens new window)
export const copyText = (text) => {
const textarea = document.createElement('textarea');
document.body.appendChild(textarea);
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.display = 'none';
textarea.focus();
textarea.select();
if (document.execCommand('copy')) {
document.execCommand('copy');
}
textarea.blur();
console.log('复制成功');
document.body.removeChild(textarea);
};
# 全屏
# 进入全屏
export const openFullscreen = (element) => {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen();
}
};
// openFullscreen(document.documentElement)
// openFullscreen(document.getElementById("id")) //某个元素
# 退出全屏
export const exitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
};
# 全屏事件
document.addEventListener("fullscreenchange", function (e) {
if (document.fullscreenElement) {
console.log('进入全屏')
} else {
console.log('退出全屏')
}
})
# 滚动到指定位置
export const scroll = (
yORxy: number | { x: number; y: number },
params?: {
smooth: boolean;
callBack: null | Function;
averageStep: number;
}
) => {
let xy = {x: 0, y: 0};
const {smooth, callback, averageStep} = {
smooth: true,
callback: null,
averageStep: 50,
...params
};
const isSmooth = smooth === undefined ? true : smooth;
if (typeof yORxy === 'number') {
xy.y = yORxy;
} else {
xy = Object.assign(xy, yORxy);
}
if (!isSmooth) {
window.scrollTo(xy.x, xy.y);
return callback && callback();
}
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
let scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
const scrollFn = () => {
if (scrollLeft === xy.x && scrollTop === xy.y) {
return callback && callback();
}
scrollTop = scrollTop - averageStep <= xy.y ? xy.y : scrollTop - averageStep;
scrollLeft = scrollLeft - averageStep <= xy.x ? xy.x : scrollLeft - averageStep;
window.scrollTo(scrollLeft, scrollTop);
requestAnimationFrame(scrollFn);
};
scrollFn();
};
# 文件下载
# 流转文件下载
/**
* 流转文件下载
* @param content
* @param filename
*/
export const downloadDoc = ( content, filename )=>{
// 兼容ie11
if(window.navigator.msSaveOrOpenBlob){
try{
const blobObject = new Blob([content]);
window.navigator.msSaveOrOpenBlob(blobObject, filename);
} catch(e){
console.log(e);
}
return;
}
const eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
const blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
window.URL.revokeObjectURL(blob); //释放掉blob对象
};
# url下载
注:url需同源
/**
* 下载
* @param url
* @param filename
*/
export const downloadUrl = ( url, filename ) => {
const eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
eleLink.href = url;
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
};
# 加载js文件
/**
* 下载
* @param src 文件路径
*/
function loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
document.body.appendChild(script);
script.onload = function() {
resolve();
};
script.onerror = function() {
reject(new Error('[register warn] script file load failed'));
};
});
}
# 加载css文件
function loadStyle(src) {
return new Promise((resolve, reject) => {
const link = document.createElement('link');
link.href = src;
link.rel = 'stylesheet';
link.type = 'text/css';
document.head.appendChild(link);
link.onload = function() {
resolve();
};
link.onerror = function() {
reject(new Error('[register warn] css file load failed'));
};
});
}
# 校验身份证
export const checkIdCard = card => {
card = card.toLowerCase();
const vcity = {
11: '北京',
12: '天津',
13: '河北',
14: '山西',
15: '内蒙古',
21: '辽宁',
22: '吉林',
23: '黑龙江',
31: '上海',
32: '江苏',
33: '浙江',
34: '安徽',
35: '福建',
36: '江西',
37: '山东',
41: '河南',
42: '湖北',
43: '湖南',
44: '广东',
45: '广西',
46: '海南',
50: '重庆',
51: '四川',
52: '贵州',
53: '云南',
54: '西藏',
61: '陕西',
62: '甘肃',
63: '青海',
64: '宁夏',
65: '新疆',
71: '台湾',
81: '香港',
82: '澳门',
91: '国外',
};
const arrint = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const arrch = ['1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2'];
let reg = /(^\d{15}$)|(^\d{17}(\d|x)$)/;
if (!reg.test(card)) return false;
if (vcity[card.substr(0, 2)] === undefined) return false;
let len = card.length;
if (len === 15) reg = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
else reg = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|x)$/;
let d,
a = card.match(new RegExp(reg));
if (!a) return false;
if (len === 15) {
d = new Date('19' + a[2] + '/' + a[3] + '/' + a[4]);
} else {
d = new Date(a[2] + '/' + a[3] + '/' + a[4]);
}
if (!(d.getFullYear() == a[2] && d.getMonth() + 1 == a[3] && d.getDate() == a[4])) return false;
if (len === 18) {
len = 0;
for (let i = 0; i < 17; i++) len += card.substr(i, 1) * arrint[i];
return arrch[len % 11] === card.substr(17, 1);
}
return true;
};