js实现下载功能的代码实例
程序员文章站
2022-03-04 15:44:27
...
本篇文章给大家带来的内容是关于js实现下载功能的代码实例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
<!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>
相关推荐:
以上就是js实现下载功能的代码实例的详细内容,更多请关注其它相关文章!
上一篇: js实现打印超市小票功能代码详解