站长图库向大家介绍了JavaScript代码,JavaScript方法等相关知识,希望对您有所帮助
本篇文章给大家分享15个项目工程必备的JavaScript代码片段,希望对大家有所帮助!

1. 下载一个excel文档
同时适用于word,ppt等浏览器不会默认执行预览的文档,也可以用于下载后端接口返回的流数据,见3
//下载一个链接 function download(link, name) { if(!name){ name=link.slice(link.lastIndexOf('/') + 1) } let eleLink = document.createElement('a') eleLink.download = name eleLink.style.display = 'none' eleLink.href = link document.body.appendChild(eleLink) eleLink.click() document.body.removeChild(eleLink)}//下载exceldownload('http://111.229.14.189/file/1.xlsx')2. 在浏览器中自定义下载一些内容
场景:我想下载一些DOM内容,我想下载一个JSON文件
/** * 浏览器下载静态文件 * @param {String} name 文件名 * @param {String} content 文件内容 */function downloadFile(name, content) { if (typeof name == 'undefined') { throw new Error('The first parameter name is a must') } if (typeof content == 'undefined') { throw new Error('The second parameter content is a must') } if (!(content instanceof Blob)) { content = new Blob([content]) } const link = URL.createObjectURL(content) download(link, name)}//下载一个链接function download(link, name) { if (!name) {//如果没有提供名字,从给的Link中截取最后一坨 name = link.slice(link.lastIndexOf('/') + 1) } let eleLink = document.createElement('a') eleLink.download = name eleLink.style.display = 'none' eleLink.href = link document.body.appendChild(eleLink) eleLink.click() document.body.removeChild(eleLink)}使用方式:
downloadFile('1.txt','lalalallalalla')downloadFile('1.json',JSON.stringify({name:'hahahha'}))3. 下载后端返回的流
数据是后端以接口的形式返回的,调用1中的download方法进行下载
download('http://111.229.14.189/gk-api/util/download?file=1.jpg')download('http://111.229.14.189/gk-api/util/download?file=1.mp4')4. 提供一个图片链接,点击下载
图片、pdf等文件,浏览器会默认执行预览,不能调用download方法进行下载,需要先把图片、pdf等文件转成blob,再调用download方法进行下载,转换的方式是使用axios请求对应的链接
//可以用来下载浏览器会默认预览的文件类型,例如mp4,jpg等
import axios from 'axios'//提供一个link,完成文件下载,link可以是 http://xxx.com/xxx.xlsfunction downloadByLink(link,fileName){ axios.request({ url: link, responseType: 'blob' //关键代码,让axios把响应改成blob }).then(res => { const link=URL.createObjectURL(res.data) download(link, fileName) }) }注意:会有同源策略的限制,需要配置转发
5. 防抖
在一定时间间隔内,多次调用一个方法,只会执行一次.
这个方法的实现是从Lodash库中copy的
/** * * @param {*} func 要进行debouce的函数 * @param {*} wait 等待时间,默认500ms * @param {*} immediate 是否立即执行 */export function debounce(func, wait=500, immediate=false) { var timeout return function() { var context = this var args = arguments if (timeout) clearTimeout(timeout) if (immediate) { // 如果已经执行过,不再执行 var callNow = !timeout timeout = setTimeout(function() { timeout = null }, wait) if (callNow) func.apply(context, args) } else { timeout = setTimeout(function() { func.apply(context, args) }, wait) } }}使用方式:
<!DOCTYPE html><html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <input id="input" /> <script> function onInput() { console.log('1111') } const debounceOnInput =

