Rumah > Artikel > hujung hadapan web > js实现下载功能的代码实例
本篇文章给大家带来的内容是关于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>
相关推荐:
Atas ialah kandungan terperinci js实现下载功能的代码实例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!