【问题标题】:JS - Change href and trigger image download when link is clickedJS - 单击链接时更改href并触发图像下载
【发布时间】:2018-12-03 11:49:52
【问题描述】:
我正在尝试使用<a> 标记上的download 属性下载图像。它的href 值在单击时更新。
function Download_Image(element) {
var mydiv = $("#imageDiv");
var Image = mydiv[0].children;
mydiv.download = Image[0].src;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imageDiv">
<img
width="200"
height="140"
src="https://2.bp.blogspot.com/-pjQRansD-ig/XAUEH2oe8tI/AAAAAAAAHwE/BgZOyaGnQLYhH2Zjxx86BRvyOs8o9yGjgCLcBGAs/s200/16e3d864-8fb8-4f43-b91e-cc97a75c602f.jpg" />
</div>
<a href="#" onclick="Download_Image(this)" download>Click here to download image</a>
但是,当我单击该链接时,它会下载整个 HTML 页面而不是图像。
【问题讨论】:
标签:
javascript
jquery
html
http
download
【解决方案1】:
您需要更改<a> 元素的href 属性,而不是<div> 的download 属性。
无论如何,download 属性 is not supported in all browsers 如果未设置 Content-Disposition: attachment 标头,则可能不适用于其他一些属性。
例如,如果我们使用带有以下代码的 Instagram 图像,则只有在 URL 末尾附加 ?dl=1 时它才会起作用:
const links = document.getElementById('links');
const image = document.getElementById('image');
links.onclick = (e) => {
const link = e.target;
if (link.tagName !== 'A') {
return;
}
link.href = `${ image.src }${ link.innerText.includes('WITHOUT') ? '' : '?dl=1' }`;
}
body {
height: 100vh;
margin: 0;
font-family: monospace;
display: flex;
align-items: center;
}
#image {
margin: 8px;
height: calc(100vh - 16px);
}
#links {
display: flex;
flex-direction: column;
}
#links > a {
display: block;
padding: 8px;
line-height: 14px;
margin: 4px 0;
color: black;
text-decoration: none;
border: 3px solid black;
border-radius: 2px;
}
#links > a:hover {
background: yellow;
}
<img id="image" src="https://scontent-mad1-1.cdninstagram.com/vp/e96d73e7938825335c235baedb51e91a/5CAAC2D4/t51.2885-15/e35/46060357_1380937935382732_6380498939567322752_n.jpg" />
<div id="links">
<a href="#" download>? WITHOUT HEADER</a>
<a href="#" download>? WITH HEADER</a>
</div>
您可以查看一个名为 download.js 的库。