前端开发中几个好用的方法汇总
// 1. 删除一个页面元素的方法
function removeElement(_element) {
if (!_element) return;
const _parentElement = _element.parentNode;
if (_parentElement) {
_parentElement.removeChild(_element);
}
}
//2. 获取视频封面的一个方法
const getVideoPreviewImg = (url, width, height) => {
width = width || 90;
height = height || 90;
/* 创建视频dom节点 */
let node = document.createElement("video");
// node.muted=true;
node.style.width = `${width}px`;
node.style.height = `${height}px`;
/* 自动播放 */
node.autoplay = true;
node.src = url;
node.volume=0.01;
node.currentTime=1;
node.setAttribute("crossOrigin", "anonymous");
/* 创建canvas节点 */
let canvasNode = document.createElement("canvas");
canvasNode.width = width;
canvasNode.height = height;
const canvasFill = canvasNode.getContext("2d");
canvasFill.drawImage(node, 0, 0, canvasNode.width, canvasNode.height);
/* 把视频变成canvas */
return new Promise(resolve => {
node.onplaying = () => {
setTimeout(() => {
canvasFill.drawImage(node, 0, 0, canvasNode.width, canvasNode.height);
/* 把canvas变成图片 */
const imgSrc = canvasNode.toDataURL("image/jpeg");
node.pause();
removeElement(node);
resolve(imgSrc);
}, 100);
};
});
};
// 3. 注册快捷键的类
class HotKeyHandler {
constructor(MainKey, SubKey, func) {
this.currentMainKey= null;
this.currentSubKey=SubKey;
this.func=func;
this.MKeycode = "";
switch (MainKey) {
case 0:
this.MKeycode = 17; //Ctrl
break;
case 1:
this.MKeycode = 16; //Shift
break;
case 2:
this.MKeycode = 18; //Alt
break;
}
document.addEventListener('keyup',(evnt)=>{
if(evnt.keyCode==this.MKeycode){
this.currentMainKey = null;
}
})
document.addEventListener('keydown',(evnt)=>{
//获取键值
var keyCode = evnt.keyCode;
var keyValue = String.fromCharCode(evnt.keyCode);
console.log("in")
if (this.currentMainKey != null) {
if (keyValue == this.currentSubKey) {
// this.currentMainKey = null;
if (this.func != null)
this.func();
}
}
if (keyCode == this.MKeycode) this.currentMainKey = keyCode;
}
)
}
}
// 4. 深度克隆一个对象
//深复制对象方法
function cloneObj (obj) {
var newObj = {};
if (obj instanceof Array) {
newObj = [];
}
for (var key in obj) {
var val = obj[key];
newObj[key] = typeof val === 'object' ? cloneObj(val): val;
}
return newObj;
}
// 5.忽略方法的深复制对象
function JsonClone(obj){
return JSON.parse(JSON.stringify(obj));
}