赞
踩
<!DOCTYPE html> <html lang="en"> <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> <div> <!-- a 标签下载 --> <a href="/04-a标签下载功能/test.png" download="demo">下载</a> <!-- 其他标签实现下载 同域 --> <div onclick="download()">下载</div> <!-- 其他标签实现下载 跨域 --> <div onclick="download1()">下载</div> </div> <script> // 同域 function download( url = '/04-a标签下载功能/test.png', title = 'demo2', artist = 'down' ) { const eleLink = document.createElement('a') // 新建A标签 eleLink.href = url || '/04-a标签下载功能/test.png' // 下载的路径 eleLink.download = `${title} - ${artist}` // 设置下载的属性,可以为空 eleLink.style.display = 'none' document.body.appendChild(eleLink) eleLink.click() // 触发点击事件 document.body.removeChild(eleLink) } // 跨域 function download1( url = 'https://upload-images.jianshu.io/upload_images/5809200-a99419bb94924e6d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240', title = 'demo3', artist = 'down' ) { var x = new XMLHttpRequest() x.open('GET', url, true) x.responseType = 'blob' x.onload = function () { const url = window.URL.createObjectURL(x.response) const eleLink = document.createElement('a') eleLink.href = url eleLink.download = `${title} - ${artist}` eleLink.style.display = 'none' document.body.appendChild(eleLink) eleLink.click() document.body.removeChild(eleLink) } x.send() } </script> </body> </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。