82个常规的前端JavaScript方法封装(71~82)
发表于:2021-12-05 17:54:35浏览:1528次
本篇文章主要介绍的是一些常用的前端JavaScript方法封装,原生dom操作,判断图片加载完成,音频加载完成操作,光标所在位置插入字符,图片地址转base64等,自己收集整理以便后期使用,需要的朋友可以阅读收藏。
71、原生dom操作
const dom = { $: function(selector) { let type = selector.substring(0, 1) if (type === '#') { if (document.querySelecotor) return document.querySelector(selector) return document.getElementById(selector.substring(1)) } else if (type === '.') { if (document.querySelecotorAll) return document.querySelectorAll(selector) return document.getElementsByClassName(selector.substring(1)) } else { return document['querySelectorAll' ? 'querySelectorAll' : 'getElementsByTagName'](selector) } }, hasClass: function(ele, name) { /* 检测类名 */ return ele.className.match(new RegExp('(\s|^)' + name + '(\s|$)')) }, addClass: function(ele, name) { /* 添加类名 */ if (!this.hasClass(ele, name)) ele.className += ' ' + name }, removeClass: function(ele, name) { /* 删除类名 */ if (this.hasClass(ele, name)) { let reg = new RegExp('(\s|^)' + name + '(\s|$)') ele.className = ele.className.replace(reg, '') } }, replaceClass: function(ele, newName, oldName) { /* 替换类名 */ this.removeClass(ele, oldName) this.addClass(ele, newName) }, siblings: function(ele) { /* 获取兄弟节点 */ console.log(ele.parentNode) let chid = ele.parentNode.children, eleMatch = [] for (let i = 0, len = chid.length; i < len; i++) { if (chid[i] !== ele) { eleMatch.push(chid[i]) } } return eleMatch }, getByStyle: function(obj, name) { /* 获取行间样式属性 */ if (obj.currentStyle) { return obj.currentStyle[name] } else { return getComputedStyle(obj, false)[name] } }, domToStirng: function(htmlDOM) { /* DOM转字符串 */ var div = document.createElement('div') div.appendChild(htmlDOM) return div.innerHTML }, stringToDom: function(htmlString) { /* 字符串转DOM */ var div = document.createElement('div') div.innerHTML = htmlString return div.children[0] } }
72、判断图片加载完成
const imgLoadAll = function(arr, callback) { // 图片加载 let arrImg = [] for (let i = 0; i < arr.length; i++) { let img = new Image() img.src = arr[i] img.onload = function() { arrImg.push(this) if (arrImg.length == arr.length) { callback && callback() } } } }
73、音频加载完成操作
const loadAudio = function(src, callback) { // 音频加载 var audio = new Audio(src) audio.onloadedmetadata = callback audio.src = src }
74、光标所在位置插入字符
const insertAtCursor = function(dom, val) { // 光标所在位置插入字符 if (document.selection) { dom.focus() let sel = document.selection.createRange() sel.text = val sel.select() } else if (dom.selectionStart || dom.selectionStart == '0') { let startPos = dom.selectionStart let endPos = dom.selectionEnd let restoreTop = dom.scrollTop dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length) if (restoreTop > 0) { dom.scrollTop = restoreTop } dom.focus() dom.selectionStart = startPos + val.length dom.selectionEnd = startPos + val.length } else { dom.value += val dom.focus() } }
75、图片地址转base64
const getBase64 = function(img) { //传入图片路径,返回base64,使用getBase64(url).then(function(base64){},function(err){}); let getBase64Image = function(img, width, height) { //width、height调用时传入具体像素值,控制大小,不传则默认图像大小 let canvas = document.createElement("canvas"); canvas.width = width ? width : img.width; canvas.height = height ? height : img.height; let ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); let dataURL = canvas.toDataURL(); return dataURL; } let image = new Image(); image.crossOrigin = ''; image.src = img; let deferred = $.Deferred(); if (img) { image.onload = function() { deferred.resolve(getBase64Image(image)); } return deferred.promise(); } }
76、base64图片下载功能
const downloadFile = function(base64, fileName) { //base64图片下载功能 let base64ToBlob = function(code) { let parts = code.split(';base64,'); let contentType = parts[0].split(':')[1]; let raw = window.atob(parts[1]); let rawLength = raw.length; let uInt8Array = new Uint8Array(rawLength); for (let i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array], { type: contentType }); }; let aLink = document.createElement('a'); let blob = base64ToBlob(base64); //new Blob([content]); let evt = document.createEvent("HTMLEvents"); evt.initEvent("click", true, true); //initEvent不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为 aLink.download = fileName; aLink.href = URL.createObjectURL(blob); aLink.click(); }
77、浏览器是否支持webP格式图片
const isSupportWebP = function() { //判断浏览器是否支持webP格式图片 return !![].map && document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0; }
78、url参数转对象
const parseQueryString = function(url) { //url参数转对象 url = !url ? window.location.href : url; if (url.indexOf('?') === -1) { return {}; } let search = url[0] === '?' ? url.substr(1) : url.substring(url.lastIndexOf('?') + 1); if (search === '') { return {}; } search = search.split('&'); let query = {}; for (let i = 0; i < search.length; i++) { let pair = search[i].split('='); query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || ''); } return query; }
79、对象序列化【对象转url参数】
const stringfyQueryString = function(obj) { //对象序列化【对象转url参数】 if (!obj) return ''; let pairs = []; for (let key in obj) { let value = obj[key]; if (value instanceof Array) { for (let i = 0; i < value.length; ++i) { pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i])); } continue; } pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])); } return pairs.join('&'); }
80、H5软键盘缩回、弹起回调
const h5Resize = function(downCb, upCb) { //当软件键盘弹起会改变当前 window.innerHeight,监听这个值变化 [downCb 当软键盘弹起后,缩回的回调,upCb 当软键盘弹起的回调] var clientHeight = window.innerHeight; downCb = typeof downCb === 'function' ? downCb : function() {} upCb = typeof upCb === 'function' ? upCb : function() {} window.addEventListener('resize', () => { var height = window.innerHeight; if (height === clientHeight) { downCb(); } if (height < clientHeight) { upCb(); } }); }
81、函数防抖
const debounce = function(func, wait, immediate) { //函数防抖[func 函数,wait 延迟执行毫秒数,immediate true 表立即执行,false 表非立即执行,立即执行是触发事件后函数会立即执行,然后n秒内不触发事件才能继续执行函数的效果] let timeout; return function() { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); if (immediate) { var callNow = !timeout; timeout = setTimeout(() => { timeout = null; }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function() { func.apply(context, args) }, wait); } } }
82、函数节流
const throttle = function(func, wait ,type) { //函数节流 [func 函数 wait 延迟执行毫秒数 type 1 表时间戳版,2 表定时器版] if(type===1){ let previous = 0; }else if(type===2){ let timeout; } return function() { let context = this; let args = arguments; if(type===1){ let now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } }else if(type===2){ if (!timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } }