Home > Article > Web Front-end > js code example to implement download function
The content of this article is about code examples for implementing the download function in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件下载</title> </head> <body> <div onclick="funDownload('1111111111','文档.txt')">点我啊</div> <div onclick="download('你棒','https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1533799465&di=0f7445fba7d177bfd21b2d71d41531fb&src=http://pic28.photophoto.cn/20130717/0010023915569244_b.jpg')">点我啊</div><div onclick="downloadUrl('https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1533799465&di=0f7445fba7d177bfd21b2d71d41531fb&src=http://pic28.photophoto.cn/20130717/0010023915569244_b.jpg')">点我啊</div> <script> function funDownload(content, filename) { // 创建隐藏的可下载链接 var eleLink = document.createElement('a'); eleLink.download = filename; eleLink.style.display = 'none'; // 字符内容转变成blob地址 var blob = new Blob([content]); eleLink.href = URL.createObjectURL(blob); // 触发点击 document.body.appendChild(eleLink); eleLink.click(); // 然后移除 document.body.removeChild(eleLink); }; function download(name,href) { var $a = document.createElement('a'); $a.setAttribute("href", href); $a.setAttribute("download",name); var evObj = document.createEvent('MouseEvents'); evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null); $a.dispatchEvent(evObj); } function downloadUrl(src){ var $a = document.createElement('a'); $a.setAttribute("href", src); $a.setAttribute("download", ""); var evObj = document.createEvent('MouseEvents'); evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null); $a.dispatchEvent(evObj); } </script> </body> </html>
Related recommendations:
How to remove specified elements from an array in js (two methods)
How to write in js css animation? How to write css animation in js (code)
The above is the detailed content of js code example to implement download function. For more information, please follow other related articles on the PHP Chinese website!