文章来源地址https://www.toymoban.com/news/detail-475964.html
<!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>
文章来源:https://www.toymoban.com/news/detail-475964.html
到了这里,关于a标签下载功能(同域和跨域)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!