时间:2021-07-01 10:21:17 帮助过:14人阅读
<!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如何写出css动画 ?js写css动画的方法(代码)
以上就是js实现下载功能的代码实例的详细内容,更多请关注Gxl网其它相关文章!